Binary search
Binary search finds a target in a sorted sequence by repeatedly discarding half of the remaining range. It runs in O(log n) comparisons and needs random access.
Detailed Explanation
Linear search asks "is this it?" n times. Binary search asks "is the target left or right of the middle?" and throws away half the list each time. After about log₂(n) steps the range is empty or you found the value. The sequence must be sorted in the same order you compare.
The loop keeps two indices, lo and hi, that bound the unsearched slice. The usual half-open form is lo = 0, hi = len(a), mid = (lo + hi) // 2. If a[mid] < target, the answer is to the right: lo = mid + 1. If a[mid] > target, hi = mid. Equality is a hit, or you keep going to find the leftmost or rightmost match.
Off-by-one errors are the whole difficulty. Infinite loops happen when mid does not shrink the range: using (lo + hi + 1) // 2 in the wrong branch, or setting lo = mid when a[mid] cannot be the answer. Write a small table of cases (empty, one element, target below all, above all, duplicate run) and test them.
bisect is the implementation you should call in production. Hand-rolled binary search is for interviews, for predicates ("first index where ok(i) is true"), and for search over an implicit range (the smallest capacity that fits, the first time a condition holds). The last case is binary search on the answer: lo and hi are values, not indices.
Binary search needs O(1) index access. It is a poor fit for a linked list. It is a good fit for a list, a tuple, and a file of fixed-size records.
Code Examples
def binary_search(items: list[int], target: int) -> int:
"""Return the index of target, or -1 if missing. items must be sorted."""
lo, hi = 0, len(items)
while lo < hi:
mid = (lo + hi) // 2
if items[mid] < target:
lo = mid + 1
elif items[mid] > target:
hi = mid
else:
return mid
return -1
print(binary_search([1, 3, 4, 7, 9], 7)) # 3
print(binary_search([1, 3, 4, 7, 9], 2)) # -1def first_true(lo: int, hi: int, pred) -> int:
"""Smallest x in [lo, hi) such that pred(x) is true; hi if none."""
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
print(first_true(0, 10, lambda n: n * n >= 30)) # 6, because 6*6 == 36Common Gotchas
Searching an unsorted list
the algorithm still returns an index. It is meaningless. Sort or keep the list ordered.
`lo = mid` when `mid` cannot be the answer
the range may not shrink. Always `mid + 1` on that branch, or use a different midpoint convention consistently.
Overflow is not a Python `int` problem
`lo + hi` cannot overflow. In other languages you write `lo + (hi - lo) // 2`. The logic bugs remain.
Duplicates need a policy
"any index" vs "leftmost" vs "rightmost". `bisect_left` / `bisect_right` name the policy.