Binary Search
If the data is sorted, you can search far faster than checking every element. Binary search looks at the middle element first. If it is the target, done. If the target is larger, it can only be in the right half; if smaller, only in the left half. Each comparison throws away half of the remaining range.
It's the strategy you use with a paper dictionary: open in the middle, see that "kiwi" comes after "giraffe", and ignore the first half.
How it works
- Keep two indexes,
lo = 0andhi = n - 1: the range where the target could still be. - While
lo <= hi: computemid = (lo + hi) // 2and comparearr[mid]with the target. - Equal: return
mid. Smaller than the target: setlo = mid + 1. Larger: sethi = mid - 1. - If the range becomes empty (
lo > hi), the target is not there.
Implementation
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
steps = 0
while lo <= hi:
mid = (lo + hi) // 2
steps += 1
print(f"range {lo}..{hi}, middle index {mid} (value {arr[mid]})")
if arr[mid] == target:
return mid, steps
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
data = [4, 11, 19, 25, 36, 42, 57, 63, 72, 88, 95]
print(binary_search(data, 72))
print(binary_search(data, 30))range 0..10, middle index 5 (value 42)
range 6..10, middle index 8 (value 72)
(8, 2)
range 0..10, middle index 5 (value 42)
range 0..4, middle index 2 (value 19)
range 3..4, middle index 3 (value 25)
range 4..4, middle index 4 (value 36)
(-1, 4)
The first search matches the animation: middle values 42, 72 and found in 2 steps. Searching for 30 narrows the range down until it is empty. Here is that search animated:
Halving is powerful
Each step halves the range, so a range of n elements is reduced to a single element after about log₂ n steps. That gives O(log n) time:
import math
def worst_case_steps(n):
steps = 0
while n > 0:
steps += 1
n //= 2 # the bigger remaining half after one comparison
return steps
for n in [10, 1_000, 1_000_000, 1_000_000_000]:
print(f"{n:>13,} elements: linear up to {n:>13,} checks, binary up to {worst_case_steps(n):>2}")
print(math.ceil(math.log2(1_000_000 + 1))) 10 elements: linear up to 10 checks, binary up to 4
1,000 elements: linear up to 1,000 checks, binary up to 10
1,000,000 elements: linear up to 1,000,000 checks, binary up to 20
1,000,000,000 elements: linear up to 1,000,000,000 checks, binary up to 30
20
A billion sorted values need at most 30 comparisons.
Finding the first occurrence and insertion points
When the array contains duplicates, plain binary search returns some matching index. A small change finds the leftmost position where the target could be inserted while keeping the array sorted. This is what Python's bisect module does:
import bisect
def lower_bound(arr, target):
lo, hi = 0, len(arr) # note: hi = len(arr), half-open range
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
scores = [10, 20, 20, 20, 30, 40]
print(lower_bound(scores, 20), bisect.bisect_left(scores, 20))
print(bisect.bisect_right(scores, 20))
print("count of 20:", bisect.bisect_right(scores, 20) - bisect.bisect_left(scores, 20))
print(lower_bound(scores, 25)) # where 25 would be inserted1 1
4
count of 20: 3
4
Binary search on the answer
Binary search works on anything monotonic: a yes/no question whose answer switches from "no" to "yes" exactly once. For example, the integer square root of n is the largest x with x * x <= n:
def integer_sqrt(n):
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2 # round up so the range always shrinks
if mid * mid <= n:
lo = mid
else:
hi = mid - 1
return lo
print([integer_sqrt(n) for n in [0, 1, 15, 16, 17, 99, 1_000_000]])[0, 1, 3, 4, 4, 9, 1000]
Common mistakes
| Mistake | Effect |
|---|---|
| Using binary search on unsorted data | wrong answers, silently |
while lo < hi with hi = n - 1 |
misses the last remaining element |
lo = mid instead of lo = mid + 1 (in the closed-range version) |
infinite loop when lo + 1 == hi |
| Re-sorting before every search | O(n log n) per search, slower than linear search |
Tip: In languages with fixed-size integers,
(lo + hi) / 2can overflow for huge arrays; writelo + (hi - lo) / 2. Python integers never overflow, so(lo + hi) // 2is fine here.
Test yourself
What must be true of the data for binary search to work?
- It must have no duplicates
- It must be sorted
- It must have an odd length
- It must be stored in a linked list
About how many comparisons does binary search need in the worst case for 1,000,000 sorted values?
- 20
- 1,000
- 500,000
- 1,000,000
In [2, 5, 8, 12, 16], which index does binary search check first?
- 0
- 1
- 2
- 4