Sub topic 7
Binary Search and Its Recurrence
Assume you know arrays, zero-based indexing, loops, logarithms, and basic recurrence notation. Binary search finds a key in a sorted array by repeatedly discarding half of the remaining range.
Working Model
Maintain two indices:
lo: first possible positionhi: last possible position
At each step, inspect the middle position.
- If the middle value equals the key, return its index.
- If the middle value is smaller, search the right half.
- If the middle value is larger, search the left half.
The search range is inclusive, so the loop continues while lo <= hi.
def binary_search(a, key):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == key:
return mid
if a[mid] < key:
lo = mid + 1
else:
hi = mid - 1
return -1
values = [3, 8, 12, 17, 25, 31]
print(binary_search(values, 17)) # 3
print(binary_search(values, 10)) # -1For the key 17, the algorithm first examines 12. Since 17 is larger, it discards [3, 8, 12]. It then examines 25, discards the larger part, and finally finds 17.
Recurrence and Complexity
If the current range contains n elements, one comparison takes constant time, and the next search has at most n/2 elements. Therefore,
\[ T(n) = T(\lfloor n/2 \rfloor) + \Theta(1) \]
Expanding the recurrence gives:
\[ T(n) = T(n/2) + \Theta(1) = T(n/4) + 2\Theta(1) = \cdots \]
The range reaches size one after approximately \(\log_2 n\) halvings. Thus the worst-case running time is \(\Theta(\log n)\).
| Case | Time | When it occurs |
|---|---|---|
| Best | \(\Theta(1)\) | The first middle element is the key |
| Average | \(\Theta(\log n)\) | Under the usual balanced-search assumption |
| Worst | \(\Theta(\log n)\) | The key is found late or is absent |
| Extra space | \(\Theta(1)\) | Iterative implementation |
A recursive implementation has the same time complexity but uses \(\Theta(\log n)\) stack space. In fixed-width integer languages, compute the midpoint as lo + (hi - lo) // 2 to avoid integer overflow. Duplicate values do not change the complexity; this version may return any matching occurrence.
Exercise
A sorted array has 1024 elements. What is the maximum number of middle-element comparisons needed by binary search?
Show answer
At most 11 comparisons, because 2^10 = 1024 and the search may need one comparison for each level plus the final one-element range.