Binary search

How does a computer find one number among a million with only 20 comparisons? Play the algorithm yourself – and with every mistake, see what your decision would cause.

Learning goal

You can carry out binary search step by step, estimate its running time and explain why the list has to be sorted.

Theory

The list is sorted. lo and hi mark the range where the target can still be; grey numbers have already been ruled out.

Binary search compares the target with the number in the middle of this range. If it is too small, it and everything to its left drop out; if it is too large, it and everything to its right.

Watch “Still possible” and compare with linear search, which checks one number after another from the left.

Listen to the explanation

Audio transcript

Imagine looking for seventeen in a sorted list. You check the middle entry and find twelve. Everything to the left is at most twelve, so you can cross out that entire half, including twelve itself. Next, check the middle of the remaining entries. Each comparison roughly halves the number of possibilities. That is why a million sorted entries need at most twenty comparisons. Before clicking the next comparison, point to the part of the list where your target could still be hiding.

Read full theory

The idea

In a sorted list you compare the number you are looking for with the middle element. If the middle is too small, the target can only be to the right of it – the whole left half drops out. If it is too large, the right half drops out. Then you repeat this with what is left.

How many comparisons?

Each comparison halves the range. With n elements you need $\lfloor \log_2 n \rfloor + 1$ comparisons in the worst case.

nlinear (at most)binary (at most)
16165
1,0001,00010
1,000,0001,000,00020

As a program (Python)

def search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        elif a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

1Explore

Click “Next comparison” and watch lo and hi move closer together. Compare it with linear search.

2Solve it yourself

Make a prediction and test it in the model. If the results differ, compare them and try again with new values.

3Expert tasks

Three tasks at advanced level: find the first occurrence of a repeated number with a loop invariant, predict a square root found by binary search on the answer, and use scaled-up running times to decide when sorting pays off. Harder than the tasks above – for advanced pupils and everyone who wants to get to the bottom of it.

🔒 Locked soon with an account

  • The first occurrence
  • Square root by halving
  • Is sorting worth it?

How you learn here

  1. ExploreYou change the simulation yourself and watch.
  2. Predict & solveFirst you predict, then you calculate, click or build – not just type in numbers.
  3. See the consequencesAfter a mistake the simulation plays out your result and shows the gap.
  4. Write it downYou note in one sentence what you noticed – only then can you go on.
  5. New numbersAfter every mistake you get a new variant. Solving it shows you have understood – guessing does not help.

Curriculum: Algorithms (searching and sorting). Binary search is usually taught in secondary computer science; the exact level depends on the school system.

For teachers: Set this lab as homework and check the proof codes of your class →

Found a mistake? Tell us – every simulation and every answer is checked by code, but people still make mistakes.