Download presentation
Presentation is loading. Please wait.
Published byMichael Carson Modified over 9 years ago
1
1 Linear and Binary Search Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
2
2 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)); }
3
3 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; }
4
4 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
5
5 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
6
6 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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.