Binary search

A Binary search is a method for finding an item called a key inside of a sorted list, an item that approximates this key, or reporting that no equal item exists. Using binary search in large databases is one example of the many uses of fast sorting, as Binary search takes $$O(\log n)$$ worst-case time.

When a Binary search is applied as part of a sorting algorithm, such as Insertion Sort, there tends to be a significant reduction in the amount of comparisons needed. As opposed to a normal Insertion Sort with average-case $$O(n^2)$$ comparisons, using a Binary search to determine the location within the sorted sublist that the key would need to be inserted reduces this average to $$O(n \log n)$$ comparisons.

Algorithm
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 an item equal to the key, the key is not in the array, and the result found is an approximation to the key.

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
Note: this code returns -1 if key not in array.

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