Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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. 86927277858978917684…

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. 72767778848586899192…

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 public static void selectionSort(int[] array){ for (int i = 0; i < array.length - 1; i++){ int min = array[i]; int indexOfMin = 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)


Download ppt "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."

Similar presentations


Ads by Google