← again tap: answer good → ↑ swipe up at the end: next
Question
How does binary search find a key in a sorted array, and why does it take only $O(\log n)$ steps?
Answer
Compare the key with the middle element of the remaining range: if it is smaller, continue in the left half, if larger in the right half, if equal you are done. Every step halves the range, so after $O(\log n)$ steps one element is left.
Binary search keeps two bounds, l (low) and h (high), around the part of the array that can still contain the key, and looks at the middle index m = ⌊(l + h)/2⌋:
- If
key == a[m]: found. - If
key < a[m]: the key can only be left of m, so set h = m − 1. - If
key > a[m]: the key can only be right of m, so set l = m + 1. - If l > h, the range is empty: the key is not in the array.
The whole method rests on the array being sorted by key. One comparison with the middle element rules out an entire half, because everything on the far side is known to be too small or too large.
Halving is what makes it fast: $n$ elements shrink to $n/2$, $n/4$, …, 1 after about $\log_2 n$ steps. That is the worst case; in the best case the key is the very first middle element and one comparison suffices. Looking for the smallest or largest key always costs the full $\log n$ steps. A sorted array of a million keys needs at most about 20 comparisons, where a linear scan could need a million. A sorted array used this way is called a search table.
Going further: the real catch with a search table is changing it. Inserting or deleting a key keeps the array sorted only by shifting all later elements, which is $O(n)$. Binary search trees aim to keep the fast search while making insertion and deletion cheap too.
Go deeper:
Binary search — the algorithm, its $O(\log n)$ bound and the classic off-by-one pitfalls in implementing it.
Question
Binary search for 7 in the sorted array 0 1 3 4 5 7 8 9 11 14 16 18 19 (indices 0–12): which elements are compared, and in which order?
Answer
8, then 3, then 5, then 7: found after four comparisons.
* Each row halves the range between l and h until l = m = h at the key. *
| Step | l | h | m | a[m] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 12 | 6 | 8 | 7 < 8: continue left, h = 5 |
| 2 | 0 | 5 | 2 | 3 | 7 > 3: continue right, l = 3 |
| 3 | 3 | 5 | 4 | 5 | 7 > 5: continue right, l = 5 |
| 4 | 5 | 5 | 5 | 7 | equal: found at index 5 |
Each row cuts the candidate range roughly in half: 13 elements, then 6, then 3, then 1. Thirteen elements need at most $\lfloor \log_2 13 \rfloor + 1 = 4$ comparisons, and that is exactly what this search took.
Notice that binary search never looks at most of the array: 0, 1, 4, 9, 11 and everything above 8 were excluded without ever being compared.