1 / 6

Search

Search. Why sort at all?. Easier to search for things in a list if they are sorted Search Use sequential or linear search for unsorted Use binary search for sorted. Binary Search. Check middle element Is this what we’re looking for? If so, we’re done.

gagan
Download Presentation

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

  2. Why sort at all? • Easier to search for things in a list if they are sorted • Search • Use sequential or linear search for unsorted • Use binary search for sorted

  3. Binary Search • Check middle element • Is this what we’re looking for? If so, we’re done. • Does what we’re looking for come before or after? • Throw away half we don’t need • Repeat with half we do need • What does this look like in Java?

  4. Recursive • Binary search is recursive • Uses indices to know where to search in the array • Calculate an index midway between the two indices • Determine which of the two subarrays to search • Recursive call to search subarray

  5. How many executions? • Check how many halves you threw away + 1 • Or check how many times you checked a middle element

  6. Tracing executions int[] arr = {13, 15, 32, 48, 60, 74, 91, 93, 99};binarySearch(arr, 93, 0, arr.length-1);

More Related