Sub topic 7
Why Binary Search Is O(log n)
This chapter assumes you have read the iterative binary search chapter and can follow its lo/hi/mid loop. It also assumes you know Big-O notation and the O(n) analysis of linear search. Here we work out exactly how many steps binary search takes, show why that number grows as log n, and cover the assumptions the bound depends on.
The Core Idea: Each Step Halves the Range
Binary search keeps a candidate range [lo, hi] that could still contain the target. Each loop iteration does a constant amount of work: it computes mid, compares a[mid] with the target, and moves one boundary. After that iteration, one of three things has happened:
- The target was found, and the search stops.
lomoved tomid + 1, so only the right part remains.himoved tomid - 1, so only the left part remains.
Suppose the range holds m elements. The element at mid is removed from consideration, and the remaining m - 1 elements are split into two parts. The larger part has at most floor(m / 2) elements. So in the worst case, the range size goes from m to floor(m / 2) in each iteration.
Counting the Iterations Exactly
Start with n elements and halve with rounding down until the range is empty. The question is how many halvings it takes to reach zero.
For n = 16 the sizes are 16, 8, 4, 2, 1, 0. That is 5 iterations. In general, the number of iterations is the number of times you can halve n before it reaches 0, which equals the number of bits in the binary form of n:
worst-case iterations = floor(log2 n) + 1
In binary, floor(m / 2) is a right shift by one bit. A number with b bits reaches zero after exactly b shifts. This explains the formula, and it also gives an exact way to compute it in Python: n.bit_length().
| n | floor(log2 n) + 1 | Linear search worst case |
|---|---|---|
| 1 | 1 | 1 |
| 16 | 5 | 16 |
| 1,000 | 10 | 1,000 |
| 1,000,000 | 20 | 1,000,000 |
| 1,000,000,000 | 30 | 1,000,000,000 |
| 4,294,967,295 | 32 | 4,294,967,295 |
Doubling n adds one iteration. Linear search takes twice as long when n doubles.
The Recurrence View
You can reach the same result with a recurrence. Let T(n) be the worst-case work on a range of size n, and let c be the constant cost of one iteration:
- T(0) = c (the final check
lo <= hifails) - T(n) = T(floor(n / 2)) + c
Unrolling gives T(n) = c + c + ... + c, with one c for each halving, plus the base case. That is about c · log2 n, so T(n) is O(log n).
The base of the logarithm does not matter in Big-O. log2 n and log10 n differ by a constant factor (log2 n = log10 n / log10 2), and Big-O ignores constant factors. People write O(log n) without a base for this reason. When you count actual steps, use base 2.
Measuring It
The code below counts loop iterations over every possible target, including values that are not in the list, and compares the worst case with the formula.
def binary_search_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 mid, steps
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
for n in [1, 7, 8, 100, 1000, 100000]:
a = list(range(0, 2 * n, 2)) # n sorted even numbers
targets = range(-1, 2 * n + 1) # every hit plus misses in every gap
worst = max(binary_search_steps(a, t)[1] for t in targets)
predicted = n.bit_length() # equals floor(log2 n) + 1
print(f"n={n:>6} worst={worst:>2} predicted={predicted:>2}")Output:
n= 1 worst= 1 predicted= 1
n= 7 worst= 3 predicted= 3
n= 8 worst= 4 predicted= 4
n= 100 worst= 7 predicted= 7
n= 1000 worst=10 predicted=10
n=100000 worst=17 predicted=17Compare n = 7 with n = 8. Seven elements form a perfectly balanced set of halvings (7, 3, 1, 0), so they need only 3 iterations. Eight elements need a fourth iteration because one side is always slightly larger.
Best, Worst, and Average Case
| Case | Iterations | Big-O | When it happens |
|---|---|---|---|
| Best | 1 | O(1) | The target is at the first `mid` |
| Worst | floor(log2 n) + 1 | O(log n) | The target is missing, or found at the deepest level |
| Average (successful) | about log2 n − 1 | O(log n) | Every present element is equally likely to be the target |
The average case is close to the worst case. Picture the order in which binary search checks positions as a balanced tree. The first mid is the root, depth 1. Two elements can be found at depth 2, four at depth 3, and 2^(d−1) at depth d. For n = 2^k − 1 the tree is full, and more than half of the elements are at the deepest level k. Averaging over all elements gives ((k − 1) · 2^k + 1) / (2^k − 1), which is close to k − 1. So a typical successful search finishes only about one iteration before the worst case.
Linear search behaves differently. Its average successful search takes about n / 2 comparisons, half of its worst case.
Comparisons per Iteration
Each iteration in the code above can do two comparisons: a[mid] == target and a[mid] < target. In the worst case that is about 2 · log2 n element comparisons. This changes the constant factor and leaves the Big-O class the same. It matters when comparisons are expensive, for example when you compare long strings. Some implementations use one comparison per iteration and check for equality once after the loop ends. The lower-bound chapter shows that style.
Space Complexity
The iterative version stores only lo, hi, and mid, so it uses O(1) extra space. A recursive version adds one stack frame per halving and uses O(log n) stack space. Python does not eliminate tail calls, so this cost is real there.
Assumptions Behind the Bound
The O(log n) result depends on conditions that are easy to break without noticing.
Constant-time random access
Reading a[mid] must take O(1) time. That holds for arrays and Python lists. It fails for linked lists, where reaching the middle means walking from the head. On a linked list, the walks across the halving steps add up to n/2 + n/4 + ... ≈ n node visits, so binary search becomes O(n) and gains nothing over a linear scan.
Constant-time comparisons
The analysis counts comparisons as O(1). If each comparison costs O(m), such as comparing strings of length m that share long prefixes, the total cost is O(m log n).
Data that is already sorted
O(log n) is the cost of one search on sorted data. Sorting first costs O(n log n) with a comparison sort. For a single search on unsorted data, sorting and then searching is slower than one O(n) scan. The final chapter covers when sorting pays off.
Why You Cannot Do Better with Comparisons
Binary search is optimal among comparison-based searches on sorted arrays. Any algorithm that learns about the array only by comparing elements to the target can be drawn as a decision tree, where each comparison is a node. The tree needs at least n + 1 outcomes: "found at index i" for each of the n positions, plus "not found". Each comparison in our search has two branches, so a tree of height h has at most 2^h leaves. Fitting n + 1 outcomes requires h ≥ log2(n + 1). In the worst case, then, every comparison-based search needs at least ceil(log2(n + 1)) comparisons, and binary search meets this bound.
Beating log n requires extra information about the data. Hash tables give expected O(1) lookups by computing positions from keys. Interpolation search averages O(log log n) on uniformly distributed numbers, but its worst case is O(n).
Exercise
A sorted array holds 5,000,000 elements. What is the maximum number of loop iterations the iterative binary search can take? How does that number change if the array grows to 10,000,000 elements?
Show answer
2^22 = 4,194,304 ≤ 5,000,000 < 2^23 = 8,388,608, so floor(log2 5,000,000) = 22 and the worst case is 22 + 1 = 23 iterations. For 10,000,000, 2^23 ≤ 10,000,000 < 2^24, so the worst case is 24 iterations. Doubling the size adds one iteration.
Exercise
A colleague implements binary search on a singly linked list by walking from the head to the middle node on every step. They claim it runs in O(log n) because it only makes O(log n) comparisons. What is the actual running time, and why?
Show answer
It runs in O(n). It does make O(log n) comparisons, but finding the middle takes time proportional to the current range: about n/2 node visits, then n/4, then n/8, and so on. That sum is about n, so the node traversal dominates and the total is O(n), the same class as linear search.
Exercise
Using the decision-tree argument, what is the minimum worst-case number of comparisons any comparison-based algorithm needs to search a sorted array of 1,000 elements, counting "not found" as an outcome?
Show answer
There are 1,001 outcomes, so the tree height h must satisfy 2^h ≥ 1,001. 2^9 = 512 is too small and 2^10 = 1,024 is enough, so at least 10 comparisons are needed in the worst case. Binary search's worst case of floor(log2 1000) + 1 = 10 iterations matches this, counting one comparison per iteration.