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. Look at the middle item of the sorted list.
- 2. If it is your target, you're done.
- 3. If your target is smaller, throw away the right half; if bigger, throw away the left half.
- 4. Repeat on the half that's left until you find it (or nothing is left).
The key formula
- how many items are in the sorted list
- 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)
- 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.
Try it yourself
- How many guesses to find one grain of sand among about 10^18 on a beach? (Hint: 2^10 is about 1000.)
- Why does binary search fail on an unsorted list? Build a 7-item list where it gives the wrong answer.
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.