Halve it again: binary search
A sorted catalogue lists a million part numbers. How many guesses do you need to find any one, or prove it isn't there?
About 40 min · 3 goals · Checked by automated tests
1.Why should I care?
Searching is the most common thing programs do with data. Linear search is simple and works on anything; binary search works only on sorted data but is staggeringly faster. Knowing exactly how much faster, and why, is your first taste of algorithm analysis.
- ◇ Implement linear search and binary search and count their comparisons.
- ◇ State when binary search applies (sorted data, random access) and when it doesn't.
- ◇ Derive the worst case of ⌈log₂(n + 1)⌉ comparisons for binary search.
2.Predict
Binary search on a sorted list of 1,000,000 items. Roughly how many comparisons in the worst case?
Guess first. Being wrong here is how the surprise works.
3.Discover
With 31 parts, pick a target and step both searches one comparison at a time. Try a part near the end and one that isn't stocked. Then switch to 127 parts: how much worse does linear search get? And binary?
Loading the interactive…
Can't use the interactive? Read a description instead
The visualiser shows a sorted list of part numbers as a strip of cells. Linear search colours cells one by one from the left. Binary search probes the middle, then the middle of the remaining half, shading the range still in play. With 31 parts binary search never needs more than 5 comparisons; linear search may need 31.
4.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1 · a fresh version every time
A sorted list holds 500 part numbers. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Practice 2
Binary search runs on the unsorted list [40, 10, 30, 20] looking for 40. What happens?
5.Watch
→ Watch the low, high and mid indexes on each step, and how the loop ends when the target is missing.
Walks through binary search on a sorted array and the off-by-one details that make or break it.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
6.Understand
Linear search
Check items from the start until you find the target or run out. It works on any list, sorted or not. Worst case: n comparisons (the target is last or absent). On average, for a present target, about n/2.
Binary search
Keep a range lo..hi. Compare the target with the middle item: equal, done; smaller, search the left half; bigger, the right half. Stop when the range is empty. It needs sorted data and fast access to any index (a list, not a file you must read line by line).
The cost of sorted
Binary search is only correct if the list really is sorted: on unsorted data it can confidently report 'not found' for an item that is there. If data arrives unsorted, you pay to sort it once (next lessons). Python's bisect module implements binary search for you.
Explain it another way
Guess a number between 1 and 100 with 'higher/lower' clues. Start at 50, then 25 or 75… you never need more than 7 guesses, because 2⁷ − 1 = 127 ≥ 100.
Linear search is O(n); binary search is O(log n). The loop invariant is: if the target is in the list, it lies within a[lo..hi]. Off-by-one mistakes (hi = mid instead of mid − 1, or lo < hi instead of lo <= hi) cause infinite loops or missed items.
Worst case W(n) = ⌈log₂(n + 1)⌉. W(7) = 3, W(8) = 4, W(1023) = 10, W(1024) = 11. The jump happens just after each 2^k − 1.
Calibration tables in embedded code are often stored sorted, and a binary search finds the right segment to interpolate in a handful of steps, fast enough to run thousands of times a second.
Derivation: Why the worst case is ⌈log₂(n + 1)⌉ comparisons
Each probe compares the target with the middle item of the current range. Either it matches, or the range shrinks to the left part or the right part, each holding at most half of what's left (excluding the middle item).
Let N(k) be the largest list that binary search can always settle in k probes. With one probe you can settle a list of 1: N(1) = 1.
With k probes, you spend one on the middle and must settle either side with k − 1 probes. So each side may hold N(k − 1) items: N(k) = 2·N(k − 1) + 1.
Solving: N(1) = 1, N(2) = 3, N(3) = 7, N(4) = 15, and in general N(k) = 2^k − 1.
So k probes suffice exactly when n ≤ 2^k − 1, that is 2^k ≥ n + 1. The smallest such k is ⌈log₂(n + 1)⌉.
Example: n = 1,000 needs ⌈log₂ 1001⌉ = 10 probes (2¹⁰ − 1 = 1023 ≥ 1000). Doubling n adds just one probe.
Worked example 1
Binary search that counts its comparisons, checked against linear search.
def binary_search(items, target):
"""Return (index or -1, comparisons) for a sorted list."""
lo, hi, comparisons = 0, len(items) - 1, 0
while lo <= hi:
mid = (lo + hi) // 2
comparisons += 1
if items[mid] == target:
return mid, comparisons
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, comparisons
parts = list(range(1000, 1124, 4)) # 31 sorted part numbers
print(binary_search(parts, 1088)) # (22, 5)
print(binary_search(parts, 1090)) # (-1, 5)
worst = max(binary_search(parts, t)[1] for t in range(990, 1130))
print(worst) # 5, and ceil(log2(32)) = 5Common mix-ups
- Binary search is always better than linear search.
✓ Only on sorted data with random access. For a single search of unsorted data, sorting first costs more than one linear scan. - Doubling the data doubles binary search time.
✓ It adds just one comparison.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3 · a fresh version every time
A sorted list holds 50 calibration points. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Practice 4
Linear search on an unsorted list of 4,096 sensor ids, looking for one that is absent. How many comparisons?
Practice 5
A student writes 'while lo < hi:' instead of 'while lo <= hi:'. What goes wrong?
8.Apply it
Use Python's bisect.bisect_left to find where a measured temperature falls in a sorted calibration table and interpolate between the two neighbouring entries. Check your own binary_search against bisect on 1,000 random targets.
9.Reflect
10.Go further
- Python docs: bisect ↗Binary search in the standard library, with examples for lookup tables.
Concepts: Algorithms, searching and complexity