Sub topic 8
Binary Search and Its Recurrence
This chapter assumes you can read Python, know asymptotic notation (O, Omega, Theta), and have seen linear search. You should also be comfortable solving a simple recurrence by repeated substitution. Binary search is the first algorithm in this tutorial whose cost comes from a recurrence, so it links loop analysis to divide and conquer.
The idea
Binary search finds a key in a sorted array. It compares the key with the middle element. If they match, it stops. If the key is larger, the key can only be in the right half. If it is smaller, the key can only be in the left half. Each comparison discards half of the remaining candidates.
The sorted order is required. Without it, one comparison says nothing about which half to discard.
The iterative version
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 -1The search window is a[lo..hi], inclusive on both ends. The loop invariant is: if the key is in the array, it lies inside a[lo..hi]. The loop ends when the window is empty (lo > hi), which means the key is absent.
Both mid + 1 and mid - 1 exclude mid, because a[mid] has already been compared. Writing lo = mid or hi = mid is a common bug. With lo = mid, the window can stop shrinking, and the loop never ends.
Tracing an example
Search for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indexes 0 to 9).
| Step | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 16 | 16 < 23, so lo = 5 |
| 2 | 5 | 9 | 7 | 56 | 56 > 23, so hi = 6 |
| 3 | 5 | 6 | 5 | 23 | found, return 5 |
Three comparisons were enough for ten elements. Linear search would have needed six.
The recurrence
The recursive form of the algorithm makes the recurrence visible. After one comparison, the problem becomes a search in one half of size at most n/2:
T(n) = T(n/2) + c, with T(1) = c'
Here c is the constant work for computing mid and comparing. Only one subproblem is solved, not two. This is why the recurrence has a single T term.
Solving by substitution
Expand repeatedly:
- T(n) = T(n/2) + c
- T(n) = T(n/4) + 2c
- T(n) = T(n/8) + 3c
- After k steps: T(n) = T(n/2^k) + kc
The recursion stops when n/2^k = 1, so k = log2 n. Then T(n) = T(1) + c log2 n, which is Theta(log n).
Solving by the Master theorem
The Master theorem handles T(n) = aT(n/b) + f(n). Here a = 1, b = 2, and f(n) = Theta(1). Compute n^(logb a) = n^(log2 1) = n^0 = 1. Since f(n) = Theta(n^0), this is the case where f(n) matches n^(logb a), so T(n) = Theta(f(n) log n) = Theta(log n).
Best, average, and worst cases
| Case | When it happens | Comparisons |
|---|---|---|
| Best | Key is at the first middle position | 1, so O(1) |
| Average | Key is equally likely at any position, or absent | about log2 n, so Theta(log n) |
| Worst | Key is absent, or found at the last possible level | floor(log2 n) + 1, so Theta(log n) |
For n = 10, the worst case is floor(log2 10) + 1 = 3 + 1 = 4 comparisons. The decision-tree view explains this. Each comparison is a node, and the tree of possible comparisons has height about log2 n. An unsuccessful search must reach the bottom.
Many GATE questions count comparisons exactly. Count each three-way test (equal, less, greater) as the question defines it. A common convention counts one comparison per loop pass, which gives the formula above. If the question counts == and < separately, the worst case is up to twice as large.
Recursive version and space
def bs_rec(a, key, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if a[mid] == key:
return mid
if a[mid] < key:
return bs_rec(a, key, mid + 1, hi)
return bs_rec(a, key, lo, mid - 1)The recursive version uses O(log n) stack space because the call depth is the number of halvings. The iterative version uses O(1) extra space. Both run in O(log n) time. Python does not remove tail calls, so the recursion depth is real here.
Edge cases and gotchas
- Unsorted input. The function returns wrong answers without raising an error. Sorting first costs O(n log n), so for a single lookup, linear search is cheaper.
- Duplicates. The code returns some matching index, not necessarily the first or last. To find the first occurrence, keep searching left after a match (
hi = mid - 1, remembermid). - Midpoint overflow. In fixed-width languages such as C or Java,
(lo + hi) / 2can overflow when the sum exceeds the integer limit. The safe form islo + (hi - lo) / 2. Python integers do not overflow, but GATE questions often test this idea. - Linked lists. Binary search needs constant-time access to the middle. On a linked list, reaching the middle takes O(n), so the total is no better than linear search.
- Off-by-one in bounds. With
hi = len(a)(exclusive upper bound) you must usewhile lo < hiandhi = mid. Mixing the two conventions causes infinite loops or missed elements.
Why it matters for later chapters
Binary search appears inside other algorithms, such as searching for an insertion position in insertion sort, which reduces comparisons but not element shifts. Merge sort and quick sort use the same divide-and-conquer shape with two subproblems instead of one. Comparing T(n) = T(n/2) + O(1) with T(n) = 2T(n/2) + O(n) shows how the number of subproblems and the combine cost change the answer from log n to n log n.
Quick reference
| Property | Binary search |
|---|---|
| Precondition | Sorted array with random access |
| Recurrence | T(n) = T(n/2) + O(1) |
| Time, best | O(1) |
| Time, average and worst | Theta(log n) |
| Space, iterative | O(1) |
| Space, recursive | O(log n) |
Exercise
An array has 1000 sorted elements. What is the maximum number of loop iterations binary search needs to report that a key is absent, and what does the recurrence T(n) = T(n/2) + 1 give for T(1000) if T(1) = 1?
Show answer
The worst case is floor(log2 1000) + 1 = 9 + 1 = 10 iterations, since 2^9 = 512 and 2^10 = 1024. The recurrence gives about log2 1000 + 1, which rounds to 10 when floors are applied to the sizes. So at most 10 comparisons are needed.
Exercise
Solve T(n) = T(n/2) + n by the Master theorem or by substitution, and explain why the answer differs from binary search.
Show answer
Here a = 1, b = 2, so n^(log_b a) = n^0 = 1. Since f(n) = n grows polynomially faster than 1 (and a f(n/b) = n/2 <= (1/2) f(n) satisfies the regularity condition), T(n) = Theta(n). The difference from binary search is the combine cost. Binary search does constant work per level, giving log n levels of constant work. This recurrence does n work at the top level, and the sum n + n/2 + n/4 + ... is dominated by the first term.
Exercise
Why does lo = mid instead of lo = mid + 1 make binary search fail, and on which input?
Show answer
When lo and hi are adjacent, for example lo = 3, hi = 4, mid = 3. If a[3] < key, setting lo = mid leaves lo = 3, so the window never shrinks and the loop runs forever. Any search for a key larger than a[3] in that window triggers it.