Sub topic 2
Binary Search: Halving the Range
This chapter assumes you can write loops and functions in Python, use zero-based indexing, and read Big-O notation. It also assumes the input list is already sorted in ascending order.
Halving the Range
Binary search keeps a range of indexes where the target could still be. On each step it checks the middle element and throws away the half that cannot contain the target.
def binary_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
print(binary_search([1, 3, 5, 7, 9, 11], 7)) # 3
print(binary_search([1, 3, 5, 7, 9, 11], 4)) # -1Why It Is O(log n)
Each step at least halves the range. After k steps, at most n / 2^k elements remain. The loop stops once fewer than one element remains, so k is about log₂ n. A list of 1,000,000 elements needs at most 20 comparisons. Linear search could need 1,000,000.
| n | Worst-case linear steps | Worst-case binary steps |
|---|---|---|
| 16 | 16 | 5 |
| 1,000,000 | 1,000,000 | 20 |
Getting the Boundaries Right with Loop Invariants
A loop invariant is a statement that holds true before every iteration. In this code the invariant is: if the target is in the list, it is at an index in the inclusive range [lo, hi].
Every line in the loop follows from that invariant:
lo <= hiis the loop condition because the inclusive range is empty only whenlo > hi.lo = mid + 1andhi = mid - 1skipmid, sincea[mid]has already been checked.
When a binary search misbehaves, write down its invariant and check that each update keeps it true.
Exercise
Someone changes the loop condition to while lo < hi but keeps everything else. What does binary_search([5], 5) return, and why?
Show answer
It returns -1. With lo = hi = 0 the condition is false at the start, so the loop never runs and the one remaining candidate is never checked. The inclusive range [lo, hi] requires lo <= hi.