LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

How does binary search find a key in a sorted array, and why does it take only $O(\log n)$ steps?

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⌋:

  1. If key == a[m]: found.
  2. If key < a[m]: the key can only be left of m, so set h = m − 1.
  3. If key > a[m]: the key can only be right of m, so set l = m + 1.
  4. 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:

  • doc Binary search — the algorithm, its $O(\log n)$ bound and the classic off-by-one pitfalls in implementing it.

From Quiz: ADS / Binary Search Trees | Updated: Nov 26, 2026