60 likes | 232 Views
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.
E N D
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. • 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?
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
How many executions? • Check how many halves you threw away + 1 • Or check how many times you checked a middle element
Tracing executions int[] arr = {13, 15, 32, 48, 60, 74, 91, 93, 99};binarySearch(arr, 93, 0, arr.length-1);