askNib

A series by Nib · for a curious adult who has never programmed

How can 20 guesses find one number in a million?

6 explainers, each one drawn by Nib. Read it here, or play it and he draws and says every page. Updated .

▶ Play from the startQuick reviewCheat sheet

the short answer

Because every guess can throw away half of what is left. Guess the middle of the range and the answer “higher” or “lower” removes half the numbers at once, so each extra guess doubles how big a range you can handle: twenty guesses reach 1,048,575 numbers, more than a million. The trick only works when the numbers are in order, and writing it down exactly, without an off-by-one slip, is harder than the idea suggests.

Part 1 of 6

How do you find a hidden number when you only hear higher or lower?

▶ Play this partIts own page

Here is a game. A friend picks a whole number from 1 to 100 and hides it. You guess, and after each guess they say only “higher”, “lower” or “correct”. How do you find the number in as few guesses as possible?

The first thing to notice is that a wrong guess is not wasted, because the answer carries information. If you guess 10 and hear “higher”, you now know the number is not 10 and also not anything below 10. A single answer crossed off ten numbers at once. Compare that with guessing 1, then 2, then 3, where each answer crosses off exactly one number.

So where you guess controls how much you learn. And you cannot choose the answer you will hear, so a sensible way to judge a guess is by its worst case. Guess 90 and hear “lower”, and you are still holding 89 possibilities, which is nearly all of them. That is a bad worst case.

The guess with the best worst case is the middle. Guess 50 and, whether you hear “higher” or “lower”, about half of the numbers vanish: either 51 to 100 remain or 1 to 49 do. No other guess protects you so well from bad luck. This one habit, always guess the middle of what is left, is the whole engine behind finding a number in a million.

Every answer is a cut, and the smartest cut is the middle, because it removes half of the numbers whatever you hear.

Part 2 of 6

Why do twenty guesses cover a million?

▶ Play this partIts own page

We can turn the question around. Instead of asking how many guesses a million numbers need, ask how big a range a given number of guesses can handle.

With one guess and nothing else, you can be sure to find one number: yours has to be right. With two guesses you can handle three numbers. Guess the middle one; if it is wrong, the answer “higher” or “lower” leaves exactly one number, which the second guess nails. The feedback is what stretches two guesses to cover three numbers rather than two.

Three guesses handle seven numbers: the middle one, plus a block of three on each side that two further guesses can finish. The pattern is that each new guess uses the old range twice, once on each side of a new middle. So the counts go 1, 3, 7, 15, 31, each one double the last, plus one. These are the powers of two, 2, 4, 8, 16, 32, each less one, because one guess is spent on the middle itself.

Doubling is startlingly fast. Ten guesses reach 1,023 numbers, about a thousand. Ten more doublings multiply that by about a thousand again, so twenty guesses handle 1,048,575 numbers, which is just over a million. Double the range to two million and you need only one more guess, twenty-one. A range of a billion would take just thirty.

Each guess doubles your reach, so a million numbers cost only twenty guesses.

Part 3 of 6

What must be true of a list before you can search it by halving?

▶ Play this partIts own page

The guessing game has a hidden assumption that is easy to miss. When you hear “higher”, you may throw away everything below your guess. That works only because numbers sit in a fixed order, so that “higher” has a meaning for every number at once.

Now try the same trick on a list that is not in order. Suppose nine name slips lie shuffled in a row and you are hunting for Chen. You open the middle slip and it says Lopez. Where is Chen? Anywhere. You have ruled out exactly one slip, the one you opened, and learned nothing about the others.

Alphabetize the slips and everything changes. The middle slip still says Lopez, but now Chen comes earlier in the alphabet, so every name after Lopez, which comes later still, can be thrown away without being looked at. One comparison, plus the guarantee that the list is in order, becomes a verdict on half the list.

That is why phone books and dictionaries are alphabetized, and it is the price of this method: if a list is not in order, you must either put it in order first or check the items one at a time. Halving is not magic. It is order doing the work.

Halving only works on an ordered list, because order lets one look at the middle speak for a whole half.

Part 4 of 6

How do you search a sorted list by halving, step by step?

▶ Play this partIts own page

Now we can state the method exactly. Take a sorted list of fifteen names. The whole list is still in play; call that the live region, the part that could still hold your target.

Look only at the middle name, the eighth. Compare it with the name you want. If it matches, you are done. If your target comes later in the alphabet, the middle name and everything before it are too early, so cross out that entire half. Eight names are gone for the price of one look, and seven remain. You never need to scan the discarded half to be sure, because the order guarantees the target cannot be there.

Then repeat the same move on what is left. The live region shrinks from fifteen to seven to three to one, so a fifteen-name list takes at most four looks. These are the doublings of the last question run backwards. In the same way, a million names take about twenty looks.

There are two ways the search can end. Either a middle name matches, and you have found it, or the live region becomes empty, and that proves the name is not in the list. An empty region is not a failure of the method: it is a correct, definite answer, “not there”.

Look at the middle, discard the half that cannot hold the answer, and repeat until you find it or run out.

Part 5 of 6

Why is binary search famously easy to get subtly wrong?

▶ Play this partIts own page

Halving sounds like one sentence, and people do it by instinct. Yet writing it down so that a computer does it correctly is a famous trap. A person silently patches small mistakes as they go; a machine does exactly what it is told and nothing more, so every fuzzy detail you skip becomes a place for a mistake.

Three details cause most of the trouble. The first is what to do with the middle item after you have checked it and it was too low. Cross it out along with everything below. If you keep it in the range, then in some situations the range stops shrinking and the search circles forever. The second is when to stop. When one item is left it could still be your target, so you must check it; only an empty range proves the target is absent. Stop one step early and the last item, which may be the answer, is never looked at.

The third is the subtlest: finding the middle. The obvious way is to add the low and high positions and halve the sum. But a computer stores whole numbers in a fixed-size box, and for a very large list the sum of two large positions can overflow the box and produce nonsense. The safe way is to start at the low end and add half of the gap between the two ends, which can never overflow. Joshua Bloch wrote about this bug in 2006: it had lain in wait for nine years or so in Java’s own library, and for about two decades in the code printed in a classic programming book.

How hard is it really? Jon Bentley, in his book Programming Pearls, reported that when professional programmers were given a couple of hours to write binary search, roughly ninety percent of their versions had bugs. The algorithm was first described in 1946, yet, as Bentley puts it, the first version that worked correctly for every size of list did not appear until 1962. The idea is easy. The details are not.

The idea of halving is simple, but it only works when the ends, the stopping point and the middle are all exact.

Part 6 of 6

Where else does halving the problem show up?

▶ Play this partIts own page

Forget numbers for a moment. What we really had was a pile of possibilities and a test that rules out half of them. That pattern turns up far outside list searching.

Programmers use it to hunt bugs. Suppose a program worked a thousand changes ago and is broken now. Test the change in the middle. If it is broken, the culprit is earlier; if it works, the culprit is later. Half the suspects are gone after one test, and about ten tests pin down one change out of a thousand. Version-control systems build this in: Git has a command, git bisect, that does exactly this over a project’s history.

The same idea wins the game of twenty questions. “Is it alive?” cuts the world roughly in two, while “Is it a toaster?” removes almost nothing. Good questions are halving questions.

There is one condition, the same one as before: each test must point to a side. Time order gives it to you for bugs, and clever questions give it to you for twenty questions. If a bug appears and disappears at random, a test no longer tells you which half holds the culprit, and halving is not safe. When you do have such a test, a million possibilities shrink to one in about twenty steps. Hunt for the question that splits evenly.

Whenever each test tells you which half holds the answer, you can find it in a handful of steps.

Binary search is the habit of asking the question that cuts the possibilities in half. Order is what makes that question possible, doubling is what makes it powerful, and exactness about ends, stopping and the middle is what keeps it correct. Twenty such questions are enough to find one number in a million.

Quick review

The whole series in a few minutes: each part's last board, its one idea, and the lines worth keeping.

Part 1

How do you find a hidden number when you only hear higher or lower?

Guess the middle, so that either answer throws away half the numbers.

  • The game is really about shrinking a range of possibilities.
  • One answer eliminates every number on the wrong side, not just your guess.
  • Where you guess decides how much a single answer can eliminate.
  • A guess is judged by its worst possible answer, not its best.
  • Guess the middle: whichever answer comes, half the range disappears.

Part 2

Why do twenty guesses cover a million?

Each extra guess doubles the range you can handle, and twenty doublings pass a million.

  • With one guess, you can handle exactly one number.
  • Two guesses handle three numbers.
  • Three guesses handle seven numbers: two sides of three, plus the middle.
  • n guesses handle 2^n minus 1 numbers.
  • Twenty guesses handle 1,048,575 numbers, enough for a million.

Part 3

What must be true of a list before you can search it by halving?

It must be in order, so that one look at the middle speaks for a whole half.

  • Halving needs a reason to throw away a whole side.
  • In a shuffled list, one peek tells you nothing about the rest.
  • In an ordered list, one peek rules out an entire side.
  • Order makes the list answer 'higher or lower' for you.

Part 4

How do you search a sorted list by halving, step by step?

Look at the middle, discard the half that cannot hold the target, repeat.

  • Begin with the whole sorted list as your live region.
  • Check the middle item, and stop if it matches.
  • Discard the half that cannot contain the target.
  • Repeat on the remaining half; the region keeps shrinking.
  • Stop on a match, or when nothing is left, which means it's absent.

Part 5

Why is binary search famously easy to get subtly wrong?

A machine cannot improvise, so every vague detail about ends, stopping and the middle becomes a bug.

  • The idea is easy; the details are where people slip.
  • Whether an edge is included decides if the window really shrinks.
  • Cut too much and the answer falls out of the window.
  • Stopping one step early or late misses or breaks the search.
  • Even computing the middle can break on very large lists.

Part 6

Where else does halving the problem show up?

Any hunt where each test tells you which half holds the answer, from bugs to twenty questions.

  • The method is a pattern, not a numbers trick: possibilities, a test, and an answer that rules out a whole side.
  • A bug hunt through 1,000 changes becomes: test the middle one, then discard half.
  • A thousand suspects need only about ten tests, the doubling arithmetic run in reverse.
  • Good questions split what remains roughly in half; poor ones peel off a single item.
  • Halving needs an ordering, or questions that truly split, so one answer discards a whole side.
  • Look for the question that splits the possibilities evenly and says which half holds the answer.

Cheat sheet

One sheet: every part's key drawing and its key line.

  1. 1. How do you find a hidden number when you only hear higher or lower? Guess the middle, so that either answer throws away half the numbers.

  2. 2. Why do twenty guesses cover a million? Each extra guess doubles the range you can handle, and twenty doublings pass a million.

  3. 3. What must be true of a list before you can search it by halving? It must be in order, so that one look at the middle speaks for a whole half.

  4. 4. How do you search a sorted list by halving, step by step? Look at the middle, discard the half that cannot hold the target, repeat.

  5. 5. Why is binary search famously easy to get subtly wrong? A machine cannot improvise, so every vague detail about ends, stopping and the middle becomes a bug.

  6. 6. Where else does halving the problem show up? Any hunt where each test tells you which half holds the answer, from bugs to twenty questions.