1 / 10

Arrays

Arrays. Part 2. Searching Arrays. Looking for a specific element in an array E.g., whether a certain score (85) is in a list of scores Linear search Binary search. Linear Search. Does someone in the class have a score of 85? How about 90? scores If found, return its index.

adsila
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays Part 2

  2. Searching Arrays • Looking for a specific element in an array • E.g., whether a certain score (85) is in a list of scores • Linear search • Binary search

  3. Linear Search • Does someone in the class have a score of 85? • How about 90? • scores • If found, return its index. • If not found, return -1.

  4. Binary Search • The scores are in ascending order. • Does someone in the class have a score of 91? • scores • If found, return its index. • If not found, return -1.

  5. Sorting Arrays • Selection sort • Insertion sort • Bubble sort • Quick sort • …

  6. Selection sort • array (before the sorting): 2 6 5 3 4 1 • array (after the sorting): 1 2 3 4 5 6 • Selection sort: keeps finding the smallest number and places it first

  7. publicstaticvoidselectionSort(int[] array){ • for(int i = 0; i < array.length - 1; i++){ • intmin = array[i]; • intindexOfMin = i; • for(int j = i + 1; j < array.length; j++){ • if(array[j] < min){ • min = array[j]; • indexOfMin= j; • } • } • array[indexOfMin] = array[i]; • array[i] = min; • } • }

  8. The Arrays Class • The java.util.Arrays class contains various methods for sorting and searching arrays. • int[] list = {9,3,7,5,8,2,6,1,10,4}; • java.util.Arrays.sort(list);

  9. Exercise 1: Strictly Identical Arrays • Two arrays list1 and list2 are strictly identical if they have the same length and list1[i] is equal to list2[i] for each i. Write a method that returns true if list1 and list2 are strictly identical: • public static boolean equal(int[] list1, int[] list2) • Write a test program that prompts the user to enter two lists of integers. Note that the first number in the input is the number of the elements in the list.

  10. Exercise 2: Identical Arrays • Two arrays list1 and list2 are identical if they have the same contents. • public static boolean equal(int[] list1, int[] list2)

More Related