Kolton Ndoj

Binary search: the 20-question superpower

When a database finds your username among millions in a blink, or you play 'guess my number' and always win

What problem does it solve?

How do you find one item in a huge sorted list without checking them one by one?

The big idea

Every question you ask should cut the possibilities in half, no matter what the answer is. Open the dictionary in the middle: if your word comes later, you've just thrown away half the book without reading it. Halving is so powerful that 20 halvings shrink a million down to one, and 33 halvings would find one person among everyone on Earth.

How it works, step by step

  1. 1. Look at the middle item of the sorted list.
  2. 2. If it is your target, you're done.
  3. 3. If your target is smaller, throw away the right half; if bigger, throw away the left half.
  4. 4. Repeat on the half that's left until you find it (or nothing is left).

The key formula

guesses=⌈log⁡2(n+1)⌉\text{guesses} = \lceil \log_2 (n+1) \rceil
nn
how many items are in the sorted list
log⁡2(n+1)\log_2 (n+1)
how many halvings it takes until no candidates are left; the +1 makes the worst case exact (7 items need 3 guesses, 8 items need 4)
⌈ ⌉\lceil\,\rceil
round up, because you can't ask 19.9 questions

How fast is it?

Logarithmic: doubling the list adds just one more step. The catch: the list must already be sorted.

Graph for Binary search: the 20-question superpower 11000110
About how many guesses a list of t items needs (log₂ t): the curve barely rises. 1000 items needs only 10 (the exact worst case is log₂(t + 1) rounded up). (drawn with the default slider values — move the sliders live)

Try it yourself

Fun fact

Writing it correctly is famously tricky: Java's built-in binary search had a bug for about nine years, because computing the middle as (low + high) / 2 overflows when the list has more than about a billion items. Joshua Bloch reported it in 2006.

Related

Open it in the Math Lab →

Theory · Beginner-friendly