100 likes | 273 Views
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.
E N D
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. • If not found, return -1.
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.
Sorting Arrays • Selection sort • Insertion sort • Bubble sort • Quick sort • …
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
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; • } • }
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);
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.
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)