Algorithms • Search: locate an item in an array of information (primitive type or objects) • Common searching algorithms includes: • Linear search • Binary search
Search • Looks sequentially at each element of a given collection of elements until either the target is found or we come to the end of the list (not found)
Search // Searches and returns the index of where the // searched element is located. // Returns -1 if the target is not found. public static int linearSearch (int[] numbers, int target) { int position = -1; //it is not found yet for (int index=0; index < numbers.length; index++) { if (numbers[index] == target) { position = index; //save the index of search element break; // OR // return index; } } return position; }
Search • It uses Divide and Conquer approach. • Pre-Condition: The search pool is sorted. • Instead of starting the search at one end, we begin in the middle • Used to look up a word in a dictionary or a name in a phone book.
Search 3. if 29 is in the list, it is in the front half of the list since it is smaller than 54. 8 15 22 29 36 54 55 61 70 73 88 0 1 2 3 4 5 6 7 8 9 10
Search 3. if 29 is in the list, it is in the front half of the list since it is smaller than 54. 4. With one comparison, we’ve eliminated half of the data 8 15 22 29 36 54 55 61 70 73 88 0 1 2 3 4 5 6 7 8 9 10
Search // Searches using a binary search // returns the index of where the searched element is located. // returns -1 if the target is not found. public static int binarySearch (int[] data, int target) { int start = 0, end = data.length-1, middle; int position = -1; //return -1 if not found boolean found = false; while (found == false && start <= end) { middle = (start + end)/2; if (data[middle] == target){ found = true; position = middle; } else if (data[middle] > target) end = middle - 1; else start = middle + 1; } return position; //return -1 if not found }
Binary Search Method • Assume an array a sorted in ascending order, and an item X • We want to write a method that searches for X within the array a, returning the index of X if it is found, and returning -1 if X is not in the array • A recursive strategy for searching a portion of the array from lo to hi is to set m to position of middle of portion of array:
Binary Search Method • If (a[m]== X), we found X, so return m • if (a[m] > X), recursively search a[lo … m-1] • if (a[m] < X), recursively search a[m+1 … hi]
Binary Search Method int bSearch(int[] a, int x, int lo, int hi) { int m = (lo + hi) /2; if(lo > hi) return -1; // base if(a[m] == x) return m; // base if(a[m] > x) return bSearch(a, x, lo, m-1); else return bSearch(a, x, m+1, hi); }