Sub topic 10
Binary Search as Recursion
This chapter assumes you have read the iterative binary search chapter and are comfortable with Python functions, the call stack, and the inclusive range [lo, hi] convention. Binary search works by throwing away half of the range on each step. The remaining half is a smaller binary search problem, so recursion expresses the algorithm directly: search the half that can still hold the target, and stop when no range is left.
The Recursive Formulation
Each call handles one subrange of a sorted list a. It looks at the middle element and does one of three things:
- Returns
-1if the range is empty (lo > hi). This is the base case for "not found". - Returns
midifa[mid] == target. This is the base case for "found". - Otherwise, calls itself on the left half or the right half and returns whatever that call returns.
def binary_search_rec(a, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
return binary_search_rec(a, target, mid + 1, hi)
return binary_search_rec(a, target, lo, mid - 1)
a = [1, 3, 5, 7, 9, 11]
print(binary_search_rec(a, 9, 0, len(a) - 1)) # 4
print(binary_search_rec(a, 4, 0, len(a) - 1)) # -1The logic matches the iterative version line for line. Where the loop wrote lo = mid + 1, the recursive version passes mid + 1 as the new lo. Where the loop condition was while lo <= hi, the recursive version tests the opposite, lo > hi, as its stopping condition.
Hiding the Bounds Behind a Wrapper
Callers should not have to pass 0 and len(a) - 1. If they pass the wrong bounds, the search breaks without any error. The usual fix is a small public wrapper around a private helper:
def binary_search(a, target):
return _search(a, target, 0, len(a) - 1)
def _search(a, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
return _search(a, target, mid + 1, hi)
return _search(a, target, lo, mid - 1)
print(binary_search([2, 4, 6, 8], 8)) # 3
print(binary_search([], 5)) # -1An empty list gives hi = -1, so the first call hits lo > hi straight away and returns -1. No special case is needed.
Tracing the Call Stack
Here is an unsuccessful search for 4 in [1, 3, 5, 7, 9, 11]:
| Call | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 5 | 5 > 4, go left |
| 2 | 0 | 1 | 0 | 1 | 1 < 4, go right |
| 3 | 1 | 1 | 1 | 3 | 3 < 4, go right |
| 4 | 2 | 1 | none | none | lo > hi, return -1 |
The -1 from call 4 is passed back up through calls 3, 2, and 1 without being changed. None of the calls does any work after its recursive call returns.
Correctness Through the Invariant
The loop invariant from the earlier chapter becomes a precondition of each call: if the target is in a, it is in a[lo..hi]. To show the function is correct, check three things:
- The first call satisfies it. The range
[0, len(a) - 1]covers the whole list. - Each recursive call keeps it. Because
ais sorted,a[mid] < targetmeans nothing at indexmidor to its left can match. That makes[mid + 1, hi]a safe range to pass on. The other branch works the same way in the other direction. - The recursion ends. Each call passes a range strictly smaller than its own, because
miditself is always excluded. A range cannot shrink forever, so you eventually reachlo > hior a match.
The third point is where the recursive version behaves differently from the loop when you get it wrong.
Common Errors
Forgetting to Return the Recursive Result
def broken(a, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
broken(a, target, mid + 1, hi) # result thrown away
else:
broken(a, target, lo, mid - 1) # result thrown away
print(broken([1, 3, 5, 7], 7, 0, 3)) # NoneThe inner call finds index 3, but the outer call drops that value and falls off the end of the function, so Python returns None. Python has no type check to catch this. The bug only shows when the target is not at the first midpoint, so a test that searches only for the middle element will pass.
Not Excluding the Midpoint
If you write _search(a, target, mid, hi) instead of mid + 1, the range can stop shrinking. With lo = 2, hi = 3, mid is 2, and the call receives (2, 3) again. An iterative loop with the same mistake hangs forever. The recursive version fails loudly instead:
RecursionError: maximum recursion depth exceeded in comparisonA correct binary search on a billion elements recurses only about 30 levels deep. If you see a RecursionError from a binary search, the range has stopped shrinking.
Recursing on Slices
Slicing looks neat but brings two separate problems:
def slice_search(a, target):
if not a:
return -1
mid = len(a) // 2
if a[mid] == target:
return mid
if a[mid] < target:
return slice_search(a[mid + 1:], target) # index is now relative
return slice_search(a[:mid], target)
print(slice_search([1, 3, 5, 7, 9, 11], 9)) # 1, but the correct index is 4First, the index comes back relative to the slice, not to the original list. You can fix that by adding the offset:
def slice_search_fixed(a, target):
if not a:
return -1
mid = len(a) // 2
if a[mid] == target:
return mid
if a[mid] < target:
r = slice_search_fixed(a[mid + 1:], target)
return -1 if r == -1 else mid + 1 + r
return slice_search_fixed(a[:mid], target)
print(slice_search_fixed([1, 3, 5, 7, 9, 11], 9)) # 4Second, and harder to see, each Python slice copies its elements. The copies cost about n/2 + n/4 + ... ≈ n element copies in total, so the search becomes O(n) time and uses O(n) extra memory. That cancels the whole reason for using binary search. Pass indices, not slices.
Cost of Recursion
| Property | Iterative | Recursive (index-based) |
|---|---|---|
| Time | O(log n) | O(log n) |
| Extra space | O(1) | O(log n) stack frames |
| Range stops shrinking | Infinite loop | `RecursionError` / `StackOverflowError` |
| Per-step overhead | Loop jump | Function call |
The O(log n) stack is small. For n = 2^31 it is at most 32 frames, well under Python's default limit of 1000. Function calls still cost more than loop iterations, so the iterative version is usually somewhat faster in CPython and the JVM.
Converting Between the Two Forms
Because every recursive call is a tail call, the conversion is mechanical:
| Recursive form | Iterative form |
|---|---|
| Parameters `lo`, `hi` | Local variables `lo`, `hi` |
| Base case `lo > hi` returns -1 | Loop `while lo <= hi`, then `return -1` |
| `return f(a, t, mid + 1, hi)` | `lo = mid + 1` |
| `return f(a, t, lo, mid - 1)` | `hi = mid - 1` |
Some people find the recursive form easier to prove correct and then convert it to a loop for production use.
The Same Function in Java
Java uses fixed-width int, so compute the midpoint with the overflow-safe form from the previous chapter:
public class RecursiveBinarySearch {
static int search(int[] a, int target) {
return search(a, target, 0, a.length - 1);
}
private static int search(int[] a, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = low + (high - low) / 2;
if (a[mid] == target) {
return mid;
}
if (a[mid] < target) {
return search(a, target, mid + 1, high);
}
return search(a, target, low, mid - 1);
}
public static void main(String[] args) {
int[] a = {1, 3, 5, 7, 9, 11};
System.out.println(search(a, 9)); // 4
System.out.println(search(a, 4)); // -1
}
}Method overloading takes the place of Python's wrapper and helper: the public two-argument method fills in the bounds and calls the private four-argument method.
Exercise
A colleague's recursive binary search returns the right index for some targets and None for others in the same sorted list. The base cases look correct. What is the most likely bug, and why does it only affect some targets?
Show answer
One or both recursive calls are missing a return statement, so the outer call throws away the inner call's result and falls off the end, returning None. Targets found at the very first midpoint return correctly from the base case without any recursion, so only targets that need at least one recursive call are affected.
Exercise
Rewrite the recursive call in the "go right" branch as _search(a, target, mid, hi). Give a concrete lo and hi where this recurses forever, and say what Python does.
Show answer
With lo = 2 and hi = 3, mid = (2 + 3) // 2 = 2. If a[2] < target, the call becomes _search(a, target, 2, 3) again with an identical range. The range never shrinks, so Python eventually raises RecursionError: maximum recursion depth exceeded.
Exercise
Why does slicesearchfixed run in O(n) time even though it makes only O(log n) calls?
Show answer
Each call slices the list, and a Python slice copies its elements. The copies have sizes of about n/2, n/4, n/8, and so on, which add up to about n. The copying dominates and makes the total time O(n), with O(n) extra memory as well. Passing lo and hi indices avoids all copying and keeps the time at O(log n).