70 likes | 238 Views
Linear and Binary Search. Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in. Linear search. class LinearAndBinarySearch { public static void main (String arg[]) { int size = 20, key = 23; int array[] = new int[size]; Initialize (array, size); // not shown
E N D
Linear and Binary Search Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Linear search class LinearAndBinarySearch { public static void main (String arg[]) { int size = 20, key = 23; int array[] = new int[size]; Initialize (array, size); // not shown PrintArray (array, size); // not shown System.out.println (“Linear search result: ” + LinearSearch (array, key)); System.out.println (“Binary search result: ” + BinarySearch (array, 0, size-1, key)); }
Linear search public static int LinearSearch (int array[], int key) { int i; for (i=0;i<array.length;i++) { if (array[i] == key) { return i; } } return -1; }
Binary search public static int BinarySearch (int array[], int start, int end, int key) { // Pre-condition: array is sorted // Caution: binary search does not work // on unsorted arrays. int mid; if (start > end) return -1; if (start == end) { if (key == array[start]) return start; else return -1; } // continued in next slide
Binary search mid = (start + end)/2; if (key == array[mid]) return mid; else if (key < array[mid]) { return BinarySearch (array, start, mid-1, key); } else { return BinarySearch (array, mid+1, end, key); } } } // end class
Run time analysis • Linear search in the worst case requires n comparisons • Binary search in the worst case requires O(log n) comparisons • Solution to T(n) = T(n/2) + O(1) • Remember that binary search can be applied to sorted arrays only