Searching wing · first described in 1946

Binary Search

Finding something in a sorted list is like guessing a number when someone tells you "higher" or "lower". If you always guess the middle, every guess throws away half of what's left.

Words to know

Play: guess my number

I'm thinking of a whole number from 1 to 100. Click a guess and I'll say whether my number is higher or lower.

Make your first guess.

Guesses: 0Numbers still possible: 100

Watch: the computer searches a shelf

A computer can't see the whole shelf at once. It can only look at one box at a time. Here are 31 numbers in order. Which one should the computer find?

Boxes binary search looked in: 0 Boxes you'd look in checking one by one from the left: –
looking in this box ruled out found it low / high: the edges of what's still possible

Why it's clever

Each look cuts the list in half. Doubling the list adds only one more look. Here is the most a binary search ever needs:

Sorted list ofMost looks needed

Checking one by one could take as many looks as there are items. For 8 billion names, that's 8 billion looks instead of 33.

Detective questions
  1. In the guessing game, what's the most guesses the middle strategy ever needs for 1 to 100? Why that number? (Hint: start with 100 and keep halving.)
  2. Binary search only works on a sorted list. Why? What could go wrong if the shelf were shuffled?
  3. When the number isn't on the shelf, how does the computer know to stop?
Curator's answers
  1. 7. Each guess leaves at most half: 100 → 50 → 25 → 12 → 6 → 3 → 1. Another way: 2 × 2 × 2 × 2 × 2 × 2 × 2 = 128, the first power of 2 bigger than 100.
  2. "My number is bigger than this box" only tells you it's to the right if everything to the right is bigger. On a shuffled shelf the number could be anywhere, so you couldn't throw half away.
  3. Low and high move toward each other after every look. When low passes high, there are no boxes left where the number could be.

From the archive

The idea is as old as looking things up in a sorted list, like a dictionary or a phone book. John Mauchly, one of the builders of the early ENIAC computer, described binary search for computers in 1946.

It looks simple, but it is famously easy to get slightly wrong. In 2006 Joshua Bloch, a programmer at Google, reported a bug in the binary search built into the Java language, which he had written himself years earlier. On lists with more than about a billion items, adding low + high made a number too big for the computer to hold. The fix was to compute the middle as low + (high − low) / 2, as this exhibit does.