Binary search is O(log n). It's worth understanding why, because "logarithmic" is one of the best things an algorithm can be.
Each comparison in binary search throws away half the remaining candidates. Start with n, then n/2, then n/4, … How many halvings until you reach 1?
n → n/2 → n/4 → … → 1
That count is log₂(n) — the number of times you can halve n before hitting 1. Equivalently, 2^(steps) = n, so steps = log₂(n).
| n | log₂(n) ≈ steps |
|---|---|
| 1,000 | 10 |
| 1,000,000 | 20 |
| 1,000,000,000 | 30 |
A billion items, found in about 30 comparisons. Doubling the data adds just one step. That's the magic of logarithmic growth — it barely moves as n explodes.
Whenever you can halve the problem each step, you get a logarithm — and logarithms are so flat that O(log n) is, for practical purposes, almost free. Keep an eye out for "sorted" or "monotonic": it's usually an invitation to turn O(n) into O(log n).