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.
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
The audio could not load. The transcript is below.
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.
| n | linear (at most) | binary (at most) |
|---|---|---|
| 16 | 16 | 5 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
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 -11Explore
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
- ExploreYou change the simulation yourself and watch.
- Predict & solveFirst you predict, then you calculate, click or build – not just type in numbers.
- See the consequencesAfter a mistake the simulation plays out your result and shows the gap.
- Write it downYou note in one sentence what you noticed – only then can you go on.
- 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.
You play binary search on a sorted list. The target can only be between lo and hi; grey numbers have already been ruled out. Each number has its index underneath.
Binary search always compares with the number in the middle of the range that is still possible, lo…hi. If it is too small, it and everything to its left drop out; if it is too large, it and everything to its right.
In the worst case means: the number is found as late as possible, or it is not in the list at all. The search is only finished when no candidate is left.
With each comparison a[mid] drops out, and in the worst case the larger of the two sides is left. So r candidates become at most
$$\lfloor r/2 \rfloor$$(halve, round down). Count the comparisons until 0 candidates are left.
lo and hi are the limits of the range where the target can still be – both indices belong to the range themselves. The loop runs as long as this range is not empty (lo ≤ hi). // is whole-number division.
A correct program has to find every number in the list, return -1 for missing numbers and always stop at some point.
Here the correct program from task 3 runs on an unsorted list. Work through it yourself step by step: find the middle of lo…hi, compare a[mid] with the target, then throw away the left or right side depending on the result – exactly as usual.
If a[mid] equals the target, the program returns mid. If the range lo…hi becomes empty, it returns -1.
A loop invariant is a statement that is true before every pass of the loop. Here: every index to the left of lo has a[i] < target, every index from hi on has a[i] ≥ target. So the result always lies in lo…hi (hi may be len(a)).
Check every assignment with two questions: does the statement stay true? And does hi − lo get strictly smaller, so that the loop ends?
Binary search on the answer: you search the range of numbers 0…n for the largest x that meets a condition – here $x\cdot x \le n$. This works because the condition is monotonic: if it holds for x, it holds for every smaller number too.
// is whole-number division: 7 // 2 = 3. Keep a table with lo, hi, mid and mid·mid, and check lo < hi after every step.
Scaling running times: if a running time grows like g(n), then
$$T(n) = T(n_0)\cdot\frac{g(n)}{g(n_0)}$$For $g(n) = n\log n$ the factor is $\frac{n}{n_0}\cdot\frac{\log n}{\log n_0}$ – the base of the logarithm does not matter.
Break-even: set the total times of both strategies for k searches equal and solve for k.