Math Fundamentals18 sections · 814 units
Open in Course

Binary Search Example (Classic log n algorithm)

Halving the search space

Binary search finds a target in a sorted array by repeatedly halving the search space. You start with nn elements, check the middle, and discard half.

After one comparison, you have at most n2\frac{n}{2} elements left. After two, at most n4\frac{n}{4}. After kk comparisons, at most n2k\frac{n}{2^k} elements remain.

You stop when the range has 11 element, so k=log2(n)k = \log_2(n). That's why binary search runs in O(logn)O(\log n) time.