TactivergeLite

Lite / Intelligent Robotic Systems / Week 5

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 · Full interactive version

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.

Predict

Binary search on a sorted list of 1,000,000 items. Roughly how many comparisons in the worst case?

  1. About 20
  2. About 1,000
  3. About 500,000
  4. About 1,000,000
Guess first, then reveal

20. Each comparison halves what's left: 1,000,000 → 500,000 → … → 1 in about 20 halvings, because 2²⁰ ≈ 1,048,576. Linear search would need up to a million.

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?

What the interactive shows (text version)

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.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: 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.

“Algorithms: Binary Search” by HackerRank (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

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

Intuitive

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.

Technical

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.

Mathematical

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.

Applied

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
  1. 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).

  2. 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.

  3. 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.

  4. Solving: N(1) = 1, N(2) = 3, N(3) = 7, N(4) = 15, and in general N(k) = 2^k − 1.

  5. So k probes suffice exactly when n ≤ 2^k − 1, that is 2^k ≥ n + 1. The smallest such k is ⌈log₂(n + 1)⌉.

  6. 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)) = 5

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

comparisons

Practice 2. Binary search runs on the unsorted list [40, 10, 30, 20] looking for 40. What happens?

comparisons

comparisons

Practice 5. A student writes 'while lo < hi:' instead of 'while lo <= hi:'. What goes wrong?

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.

Reflect

Explain to a friend, without code, why a million items need only about twenty guesses.

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Breadth-first search: a queue explores a mapInsertion sort: tidy as you go →