Binary search: how to explain it to a child

Binary search explained with a number guessing game: why 7 questions are enough for 100 numbers, what the algorithm looks like step by step and which mistakes children make.

Updated:

An algorithm's flowchart in Looponi during a run, with the current values of the variables next to it

Binary search is one of the first algorithms where a child sees that a clever method beats patience. The easiest way to start is with a game.

The game: guess the number

Think of a number from 1 to 100. The child guesses, and you answer only “too low”, “too high” or “got it”.

At first children guess blindly or ask in order: 1, 2, 3… That's the moment to ask which number is worth starting with, so that as many numbers as possible are sure to drop out. The answer is the middle: 50.

Why the middle

After asking about 50, half of the numbers are left, whatever the answer. After the next question, a quarter. The range shrinks like this: 100, 50, 25, 13, 7, 4, 2, 1. That's seven questions. For a thousand numbers ten are enough, and for a million, twenty.

Asking in order, you would need a hundred questions in the worst case.

The algorithm step by step

  1. Remember the two ends of the range: left and right.
  2. Work out the middle.
  3. If the middle is the number you are looking for, stop.
  4. If it is too low, move left to just past the middle. If it is too high, move right to just before the middle.
  5. Go back to step 2.

It's a loop with a decision inside and two variables that move towards each other.

Where it comes in handy

There is one condition: the data has to be ordered.

Common mistakes

In Looponi

Binary search is one of the algorithms on the track for grades 7–8. The pupil builds it as a flowchart, guesses how many times the loop will go round, and watches the ends of the range move towards each other with every step.

Frequently asked questions

What is binary search?

It's a way of searching ordered data in which every question rules out half of the possibilities. We check the middle and go left or right.

How many questions does it take to guess a number from 1 to 100?

At most 7. Each question halves the range: 100, 50, 25, 13, 7, 4, 2, 1.

Why does the data have to be ordered?

Because only then does the answer “too low” or “too high” tell you which half can be ruled out. With jumbled data you have to check the items one by one.

At what age can this be taught?

An eight-year-old already understands the number guessing game. The algorithm itself, with variables, is worth introducing at about 12–13.

Read next

All guides →