Sub topic 10
Binary Search as Recursion
This chapter assumes you have read the iterative binary search chapter and know its inclusive range [lo, hi]. You should also be comfortable with recursion, meaning a function that calls itself on a smaller input. The recursive version makes the same decisions as the loop. The only difference is that each step becomes a function call instead of a loop iteration.
The Same Halving, Expressed as Calls
Each pass through the iterative loop narrows [lo, hi] and runs again. A recursive function can do the same work by calling itself with the narrowed bounds. Each loop exit then has a matching part in the function:
- Base case: if
lo > hi, the range is empty and the target is absent, so the function returns-1. - Found case: if
a[mid] == target, the function returnsmid. - Recursive case: the function calls itself on the half that can still contain the target.
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)) # 4The invariant is the same as in the loop: if the target is in the list, it lies in a[lo..hi]. Each call keeps that promise and passes a strictly smaller range to the next call. Because the range keeps shrinking, the recursion must end.
Tracing a Call
Here is the search for 9 in [1, 3, 5, 7, 9, 11]:
The answer is found in the deepest call. Every call above it passes the answer back up unchanged.
A Friendlier Entry Point
Callers should not have to pass 0 and len(a) - 1 themselves. A small wrapper hides those arguments:
def binary_search(a, target):
return binary_search_rec(a, target, 0, len(a) - 1)
print(binary_search([1, 3, 5, 7, 9, 11], 11)) # 5
print(binary_search([], 3)) # -1For an empty list, hi is -1. The base case fires right away and the function returns -1.
Common Errors
- Slicing instead of passing bounds. Writing
binary_search_rec(a[mid+1:], target)copies part of the list on every call. That copying costs O(n) time in total, which cancels the benefit of halving. It also changes the indices, so the returned position is relative to the slice and is wrong for the original list. - Wrong base case. If you use
lo >= hiwith inclusive bounds, a one-element range is never checked. - Off-by-one bounds. If you pass
midinstead ofmid + 1ormid - 1, a two-element range can recurse forever. This is the same mistake as in the loop version.
Iterative or Recursive?
| Aspect | Iterative | Recursive |
|---|---|---|
| Time | O(log n) | O(log n) |
| Extra space | O(1) | O(log n) call stack |
| Readability | Explicit loop state | Mirrors the divide-and-conquer idea |
| Risk | Boundary bugs | Boundary bugs plus a missing `return` |
The stack depth is about log₂ n. For a billion elements, that is roughly 30 frames, well below Python's default recursion limit of 1000. Python does not remove tail calls, so each call still takes a stack frame. In production code, most people use the iterative version or a library function. The recursive form is useful when you are learning, proving correctness, or writing related divide-and-conquer algorithms.
Exercise
Trace binarysearchrec([1, 3, 5, 7, 9, 11], 4, 0, 5). List the (lo, hi) of every call and the final result.
Show answer
(0, 5): mid=2, a[2]=5 > 4, so the next call is (0, 1). (0, 1): mid=0, a[0]=1 < 4, so the next call is (1, 1). (1, 1): mid=1, a[1]=3 < 4, so the next call is (2, 1). (2, 1): lo > hi, so this call returns -1. That makes four calls, and the final result is -1.
Exercise
A teammate writes binary_search_rec(a[:mid], target, ...) for the left half. Name two problems with this.
Show answer
First, slicing copies elements, which adds O(n) work in total and removes the O(log n) advantage. Second, any index found inside a slice is relative to that slice. For right-half slices in particular, the returned index will not match the original list unless you add an offset.