Sub topic 7
Binary Search: Discarding Half the Input
This chapter assumes you can read Python loops and indexes, know Big-O notation, and have seen the recurrence T(n) = T(n/2) + O(1) from the chapters on recurrences and the master theorem.
Binary search finds a target value in a sorted list. One comparison against the middle element tells you which half cannot contain the target, so you throw that half away. As a divide-and-conquer algorithm it has these parts:
- Divide: pick the middle index.
- Conquer: continue in only one half.
- Combine: nothing. The answer from the remaining half is the answer for the whole list.
The Half-Open Range Version
The code below keeps a half-open range [lo, hi). That means lo is included and hi is not. The range is empty exactly when lo == hi.
def binary_search(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo if lo < len(a) and a[lo] == target else -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3Here is the trace for target 7:
| lo | hi | mid | a[mid] | action |
|---|---|---|---|---|
| 0 | 5 | 2 | 5 | 5 < 7, set lo = 3 |
| 3 | 5 | 4 | 9 | set hi = 4 |
| 3 | 4 | 3 | 7 | set hi = 3 |
| 3 | 3 | – | – | loop ends, a[3] == 7, return 3 |
The loop does not stop when it first sees 7. It keeps narrowing until the range is empty, and lo ends up at the first position whose value is >= target. Because of this, the same loop also gives you the insertion point, which is what Python's bisect_left returns.
Why It Is Correct
The loop keeps this invariant: every element before lo is < target, and every element at or after hi is >= target. Both updates preserve it because the list is sorted. Each iteration makes hi - lo strictly smaller: mid satisfies lo <= mid < hi, so both mid + 1 and mid shrink the range. That guarantees the loop terminates. When it ends, lo == hi, and that index is the boundary between smaller and larger elements.
Running Time
Each iteration does constant work and halves the range, so T(n) = T(n/2) + O(1). By case 2 of the master theorem, T(n) = O(log n). A list of one billion elements needs about 30 comparisons.
Common Errors
- Writing
lo = midinstead oflo = mid + 1can loop forever. Whenhi = lo + 1,midequalslo, so the range never shrinks. - Running it on unsorted input returns wrong answers without any error.
- Returning
lowithout checkinga[lo] == targetreports the insertion point as if it were a match. - In languages with fixed-width integers,
(lo + hi) / 2can overflow. Uselo + (hi - lo) / 2. Python integers do not overflow.
Exercise
At most how many loop iterations does this binary search perform on a list of 1,000,000 elements?
Show answer
About 20. Each iteration halves the range, and 2^20 = 1,048,576 ≥ 1,000,000, so after 20 halvings the range is empty.
Exercise
Change lo = mid + 1 to lo = mid and call binary_search([1, 3], 5). What happens, and why?
Show answer
It loops forever. With lo = 0 and hi = 2, mid = 1 and a[1] = 3 < 5, so lo becomes 1. Then lo = 1 and hi = 2, so mid = 1 again, and lo stays 1. The range never shrinks.