1 / 6

Linear and Binary Search

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

rgamez
Download Presentation

Linear and Binary Search

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linear and Binary Search Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

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

More Related