Binary search is one of the clearest examples of how a small change in strategy can transform an algorithm. Instead of checking every value from the beginning, it repeatedly discards half of the remaining search space.
The core idea
Imagine a sorted row of 32 numbered cards. A linear search may inspect all 32. Binary search checks the middle card first. If the target is smaller, everything to the right can be ignored. If it is larger, everything to the left can be ignored.
After one comparison, 32 possibilities become 16. Then 16 become 8, 8 become 4, and 4 become 2. This repeated halving is why binary search runs in O(log n) time.
A visual walkthrough
Suppose we want to find 23 in this sorted list:
[3, 7, 11, 15, 19, 23, 27, 31, 35]
- Check the middle: the middle value is 19.
- Compare: 23 is greater than 19, so discard 19 and everything before it.
- Check the new middle: in
[23, 27, 31, 35], choose 27. - Compare again: 23 is smaller than 27, so discard 27 and everything after it.
- Finish: the remaining candidate is 23.
The answer required only three comparisons. A linear scan would have needed six.
The condition that makes it work
Binary search needs structure. For a direct value lookup, the data must be sorted. More generally, the question being tested must be monotonic: once the answer changes from no to yes, it must not change back again.
This broader form lets binary search solve more than lookups. It can find the smallest capacity that completes a task, the earliest day a threshold is reached, or the first position where a condition becomes true.
A dependable implementation
left = 0
right = length - 1
while left <= right:
middle = left + (right - left) // 2
if values[middle] == target:
return middle
if values[middle] < target:
left = middle + 1
else:
right = middle - 1
return not_found
Common mistakes
- Using binary search on unsorted data.
- Mixing inclusive and exclusive boundary rules.
- Forgetting to move past the middle element.
- Returning any match when the problem asks for the first or last match.
- Ignoring empty input or a missing target.
How to reason about correctness
At every step, maintain one promise: if the target exists, it remains inside the current search interval. Each comparison removes only the half that cannot contain the answer. When the interval becomes empty, the target is not present.
When to reach for binary search
Look for sorted collections, ordered answer spaces, and questions containing phrases such as “first valid,” “smallest possible,” “largest allowed,” or “minimum capacity.” These are strong clues that repeated halving may work.
Download the free Algorithms Made Simple Quick Reference, or explore the full visual guide on the Algorithms Made Simple book page.
