Linear and Binary Search - PowerPoint PPT Presentation

About This Presentation
Title:

Linear and Binary Search

Description:

System.out.println ('Binary search result: ' BinarySearch (array, 0, size-1, key) ... on unsorted arrays. int mid; if (start end) return -1; if (start == end) ... – PowerPoint PPT presentation

Number of Views:4036
Avg rating:3.0/5.0
Slides: 7
Provided by: iit1
Category:

less

Transcript and Presenter's Notes

Title: Linear and Binary Search


1
Linear and Binary Search
  • Instructor Mainak Chaudhuri
  • mainakc_at_cse.iitk.ac.in

2
Linear search
  • class LinearAndBinarySearch
  • public static void main (String arg)
  • int size 20, key 23
  • int array new intsize
  • 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 (i0iltarray.lengthi)
  • if (arrayi 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 gt end) return -1
  • if (start end)
  • if (key arraystart) return start
  • else return -1
  • // continued in next slide

5
Binary search
  • mid (start end)/2
  • if (key arraymid) return mid
  • else if (key lt arraymid)
  • return BinarySearch (array, start,
    mid-1, key)
  • else
  • return BinarySearch (array, mid1, 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
Write a Comment
User Comments (0)
About PowerShow.com