Binary Search
On a sorted array, binary search checks the middle and throws away half each step: O(log n). A million items need only about 20 checks.
Binary search finds items in sorted data in O(log n), and the same idea - halving the search space - solves many "find the minimum value that works" problems.
Example
Lower bound: the first item >= x
Example
Binary search on the answer
Sometimes you search over possible answers. Example: the smallest packing speed (orders per day) to pack all the batches in 8 days, one batch at a time:
Example
Key points
- Needs sorted data.
- Use lo + (hi - lo) / 2 to avoid overflow.
- Binary search on the answer for optimisation problems.
📝 Test yourself
1. What must be true before binary search?
2. Why write lo + (hi - lo) / 2?
3. Fill in the Java library method:
Arrays.(prices, 1299)
