Binary search
Looking up a word in a dictionary, you don't read every page: you open the middle, see whether your word comes before or after, and throw away half the book. That's binary search: on sorted data, each step halves the search space, so a million items need only about 20 comparisons. It's simple to describe and famously easy to get subtly wrong.
The algorithm
O(log n): 2²⁰ ≈ 1,000,000, so 20 halvings reach a single item.
Getting the details right
- Loop condition
lo <= hi: the range[lo, hi]is inclusive, so a one-item range must still be checked. - Move past
mid(mid + 1,mid - 1), or the loop can get stuck forever. - Overflow: in languages with fixed-size integers (Java, C++),
(lo + hi) / 2can overflow; writelo + (hi - lo) / 2. Python's integers don't overflow. - It only works on sorted data (or, more generally, on a condition that flips from false to true once).
Python's bisect module
Finding boundaries
Most real binary-search problems ask "where does the answer start?". Search for the first position where a condition becomes true:
Binary search on the answer
Sometimes you binary-search over possible answers instead of an array. A factory must ship parcels (in order) within days days; what's the smallest truck capacity that works? If a capacity works, any larger one works too, so the condition flips once:
O(n log S), where S is the sum of the weights. The same trick answers "minimum speed to finish in time", "largest minimum distance", and many scheduling problems.
Rotated sorted arrays
[15, 18, 22, 3, 6, 9, 12] was sorted, then rotated. At any mid, one half is still sorted, which tells you where to look:
Binary search everywhere
- Databases keep indexes in B-trees, a many-way generalisation of binary search, so finding a row among billions takes a few disk reads.
git bisectbinary-searches your commit history for the commit that introduced a bug.- Debugging: comment out half the code, see if the bug remains, repeat.
Practice
- Find the first and last positions of a target in a sorted list with duplicates (two boundary searches).
- Find the minimum element of a rotated sorted array in O(log n).
- Koko eats bananas: piles
[3, 6, 7, 11], 8 hours. What's the slowest eating speed (bananas per hour) that finishes in time?
1.How many comparisons does binary search need for 1,000,000 sorted items, at most?
2.What does binary search require of the data?
3.What does "binary search on the answer" mean?