Sub topic 7
Why Binary Search Is O(log n)
This chapter assumes you know the iterative binary search from the previous chapter, the lo/hi/mid version that works on a sorted list. You should also be comfortable reading Big-O notation and know what a logarithm is. Here we work out how many steps that loop takes, and why the count grows so slowly.
The range shrinks by half each step
Each pass through the loop compares the target to one element, a[mid]. If they don't match, the loop throws away mid and every element on the wrong side of it. That leaves at most half of the range that was there before.
If the list starts with n elements, the most that can remain is:
- after 1 step: n / 2
- after 2 steps: n / 4
- after k steps: n / 2^k
The loop stops when the range is empty. So the question is how many times you can halve n before nothing is left. The answer is about log₂ n. More precisely, the worst case needs ⌊log₂ n⌋ + 1 comparisons.
With 16 elements, the worst case is 5 comparisons, which matches ⌊log₂ 16⌋ + 1 = 5.
Best, worst, and average case
| Case | When it happens | Comparisons | Big-O |
|---|---|---|---|
| Best | Target is at the first `mid` | 1 | O(1) |
| Worst | Target is missing, or found on the last step | ⌊log₂ n⌋ + 1 | O(log n) |
| Average | Target present, every position equally likely | about log₂ n − 1 | O(log n) |
The average case is close to the worst case. About half the elements sit at the deepest level of halving, so most successful searches take nearly the full number of steps.
Measuring it
The function below counts loop iterations. Searching for n in [0, 1, ..., n-1] always fails and always moves right, which gives the worst case. In Python, n.bit_length() equals ⌊log₂ n⌋ + 1 for positive n.
def count_steps(a, target):
lo, hi = 0, len(a) - 1
steps = 0
while lo <= hi:
steps += 1
mid = (lo + hi) // 2
if a[mid] == target:
return steps
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return steps
for n in [1, 10, 100, 1000, 10**6]:
a = list(range(n))
print(n, count_steps(a, n), n.bit_length())Output:
1 1 1
10 4 4
100 7 7
1000 10 10
1000000 20 20Compared with linear search
Linear search's worst case grows with n. Binary search's worst case grows by one each time n doubles.
| n | Linear search worst case | Binary search worst case |
|---|---|---|
| 10 | 10 | 4 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
| 1,000,000,000 | 1,000,000,000 | 30 |
What the O(log n) bound assumes
Two assumptions are built into the bound, and both are easy to overlook:
- Constant-time indexing. Reading
a[mid]must take O(1). On a linked list, reaching the middle means walking from the head, which costs O(n) per step, so you lose the advantage. - Data that is already sorted. Sorting costs O(n log n). If you sort once just to do one search, a single linear scan would have been cheaper. The log n payoff comes when you search the same sorted data many times. A later chapter covers that trade-off.
Exercise
A sorted array has 5,000,000 elements. What is the maximum number of comparisons the iterative binary search makes, and roughly how many does linear search make in its worst case?
Show answer
Binary search makes at most ⌊log₂ 5,000,000⌋ + 1 = 22 + 1 = 23 comparisons, because 2^22 = 4,194,304 ≤ 5,000,000 < 2^23. Linear search makes up to 5,000,000 comparisons.
Exercise
You double the size of a sorted array from n to 2n. How does the worst-case number of binary search comparisons change?
Show answer
It goes up by exactly one. Halving 2n once gives n, and from there the search takes the same number of steps as before.