Binary search

A Binary search is a method for finding a item called a key inside of a sorted list, or report that no such item exists. Using binary search in datsbases is one example of the usefulness of sorting, as Binary search takes $$O(\log n)$$ worst-case time.

= Explanation = To find an item in a sorted array, compare the item to the middle of the array. If it is less, repeat with the left half. If it is greater, repeat with the right half. If you get down to a single element without finding the key, the key is not in the array.

= Example = Take the list {1 2 4 5 19 24 30 31 32 40 45 98 102 104 615}.

let's say we want to search for the item 98.

first, take the middle (32).

compare the key. It is greater, so repeat with the right half.

{40 45 98 102 104 615}

first, take the middle (102).

compare the key. It is less, so repeat with the left half.

{20 45 98}

first, take the middle (45).

compare the key. It is greater, so repeat with the right half.

{98}

first, take the middle (98).

compare the key. It is equal, so done.

2nd example:

Take the list {10 14 15 30 35 62 71 100 156 157 222 245 312 755 1081}.

let's say we want to search for the item 16.

first, take the middle (100).

compare the key. It is less, so repeat with the left half.

{10 14 15 30 35 62 71}

first, take the middle (30).

compare the key. It is less, so repeat with the left half.

{10 14 15}

first, take the middle (14).

compare the key. It is greater, so repeat with the right half.

{15}

first, take the middle (15).

compare the key. It is greater, and the subarray cannot be divided, so done (key not in array).

= Pseudocode = procedure binary_search(array arr,elem key) do int lo = 0 int hi = length(arr) - 1 int mid = 0 while lo < hi do mid = lo + floor((hi - lo) / 2) if arr[mid] == key do return mid end if if arr[mid] < key do hi = mid - 1 end if if arr[mid] > key do lo = mid + 1 end if end while return -1 end