Sub topic 2
Base Cases and Why Recursion Terminates
This chapter assumes you can write and trace recursive functions in Python, read Big-O notation, and work with list slicing and index ranges. It covers two related questions. What should a divide-and-conquer algorithm do when the input is small enough to solve directly? And how can you be sure that every chain of recursive calls reaches that point? The next chapter uses the answers to prove correctness by induction.
What a Base Case Does
A base case is an input that the function solves directly, without making a recursive call. Every recursive call has to end in one. In divide and conquer, the base case is usually the smallest input for which "divide" makes no sense: an empty list, a single element, or an exponent of zero.
A base case has two jobs:
- It must return the correct answer for those inputs.
- It must catch every input that the divide step cannot shrink.
Most bugs come from the second job. A base case can be correct and still miss an input on which the split stops making progress.
The Termination Argument: A Shrinking Measure
To show that recursion terminates, pick a measure. A measure is a function of the arguments that produces a non-negative integer. Then check two facts:
- Every recursive call receives arguments with a strictly smaller measure than the current call.
- Every input that cannot be made smaller is handled by a base case.
Non-negative integers cannot decrease forever, so every chain of calls must stop. For array algorithms the measure is usually the length of the range, hi - lo. For fast exponentiation it is the exponent n.
The word strictly matters here. If a call ever receives a subproblem as large as its own input, the measure can stay the same forever, and Python eventually raises RecursionError.
The Classic Bug: A Split That Doesn't Shrink
Here is a range sum that splits at the midpoint and has only an empty-range base case:
def bad_sum(a, lo, hi):
# Intended: sum of a[lo:hi]
if hi - lo == 0:
return 0
mid = (lo + hi) // 2
return bad_sum(a, lo, mid) + bad_sum(a, mid, hi)
try:
print(bad_sum([1, 2, 3], 0, 3))
except RecursionError:
print("RecursionError: a size-1 range never shrinks")Trace a range of size 1, where hi = lo + 1. Then mid = lo, so the left call gets [lo, lo), which has size 0 and is fine. The right call gets [lo, lo + 1), which is the same range it started with. The measure stayed at 1, and the recursion never ends.
The fix is to handle every size the split cannot reduce:
def range_sum(a, lo, hi):
# Sum of a[lo:hi]
if hi - lo == 0:
return 0
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
return range_sum(a, lo, mid) + range_sum(a, mid, hi)
print(range_sum([1, 2, 3], 0, 3)) # 6
print(range_sum([], 0, 0)) # 0Now check the measure. When hi - lo >= 2, mid lies strictly between lo and hi, so both halves are non-empty and both are smaller than the original. Sizes 0 and 1 are base cases. Every call either stops or shrinks.
Termination Across the Tutorial's Algorithms
The table lists the measure and base cases for algorithms covered later in this tutorial. It also shows why each call makes progress.
| Algorithm | Measure | Base case(s) | Why each call shrinks |
|---|---|---|---|
| Binary search (half-open `[lo, hi)`) | `hi - lo` | loop stops when `lo == hi` | `lo = mid + 1` or `hi = mid`, and `lo <= mid < hi` |
| Merge sort | `len(a)` | `len(a) <= 1` | halves have length `n // 2` and `n - n // 2`, both less than `n` when `n >= 2` |
| Fast exponentiation | `n` | `n == 0` | `n // 2 < n` for `n >= 1` |
| Quickselect | `len(a)` | returns the pivot when `k` falls in the pivot block | `lows` and `highs` both exclude the pivot |
| Karatsuba | `x + y` | `x < 10` or `y < 10` | every recursive pair has a strictly smaller sum |
Some of these rows hide a trap.
Binary search: `mid` versus `mid + 1`
With a half-open range, writing lo = mid instead of lo = mid + 1 breaks termination. When hi - lo == 1, mid == lo, so lo = mid changes nothing and the loop runs forever. The rule is that each update must exclude mid from at least one side.
Quickselect: strict comparisons matter
Quickselect builds lows with x < pivot and highs with x > pivot, and it counts the copies of the pivot separately. Suppose you used x <= pivot for lows instead. On a list where every element is equal, lows would be the whole list, and the recursion would never shrink. Counting duplicates of the pivot separately guarantees that the pivot value is removed from both sides.
Karatsuba: the measure is not one argument's size
For karatsuba(x, y), the split point m comes from the larger operand. If x is much smaller than y, then hi_x can be 0, and lo_x + hi_x equals x. So x alone does not always shrink. The sum x + y does. The larger operand has hi >= 1 and m >= 1, so it satisfies hi * 2**m + lo > hi + lo, and the other operand never grows. When no single argument works as a measure, look for a combination of arguments that does.
Choosing a Good Base Case
The smallest correct base case is not always the best one. Here is what each choice costs and gains:
- Too small, or missing a size: the recursion fails to terminate, as
bad_sumdid. This is a correctness bug. - Minimal and complete (for example,
len(a) <= 1in merge sort): this is easy to reason about. The cost is a function call for every tiny subproblem. - Larger cutoff (for example, insertion sort when
len(a) <= 16): this is faster in practice. The base case then has to be a correct algorithm in its own right. The final chapter covers cutoffs.
Also make sure the base case covers inputs a caller can actually pass. max_subarray(a, lo, hi) from the spine has the base case hi - lo == 1 and no case for an empty range. That is fine because the maximum of a non-empty slice is undefined for empty input. Still, the function should either reject [] or document that it requires non-empty input. Otherwise it reaches mid = lo and recurses on an empty range forever.
def max_subarray_safe(a):
if not a:
raise ValueError("max_subarray requires a non-empty list")
return max_subarray(a, 0, len(a))
def max_subarray(a, lo, hi):
if hi - lo == 1:
return a[lo]
mid = (lo + hi) // 2
best_left = max_subarray(a, lo, mid)
best_right = max_subarray(a, mid, hi)
s, left_cross = 0, float('-inf')
for i in range(mid - 1, lo - 1, -1):
s += a[i]
left_cross = max(left_cross, s)
s, right_cross = 0, float('-inf')
for i in range(mid, hi):
s += a[i]
right_cross = max(right_cross, s)
return max(best_left, best_right, left_cross + right_cross)
print(max_subarray_safe([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6Exercise
A recursive maximum function uses mid = (lo + hi + 1) // 2, recurses on [lo, mid) and [mid, hi), and has only the base case hi - lo == 0, which returns negative infinity. For which range size does it fail to terminate, and what base case fixes it?
Show answer
Size 1 fails. With hi = lo + 1, mid = (2*lo + 2) // 2 = lo + 1 = hi. The left call gets [lo, hi), the same range again, so the measure never shrinks. Adding a base case for hi - lo == 1 that returns a[lo] fixes it, because for sizes of 2 or more, mid lies strictly between lo and hi.
Exercise
Someone changes power(x, n) so that its only base case is n == 1, which returns x. Does it terminate for every integer n >= 0? Give the measure argument.
Show answer
No. For n >= 1, n // 2 < n, and the chain of calls reaches n = 1, where it stops. When n = 1, the n // 2 = 0 call is never made, because the base case returns first. But a direct call with n = 0 is never caught: it computes 0 // 2 = 0, so the measure stays at 0 and the function recurses until RecursionError. The base case has to cover n == 0, either alone or alongside n == 1.
Exercise
In quickselect, why is it safe to recurse on highs with k - len(lows) - num_pivots, and why does the recursion on highs always shrink even when the list has many duplicates?
Show answer
The answer's rank among highs is k minus the number of elements known to be smaller (lows plus every copy of the pivot). highs holds only elements strictly greater than the pivot, so every copy of the pivot value is left out. Because num_pivots >= 1, len(highs) <= len(a) - 1. The measure len(a) drops by at least 1 even when the list is all duplicates.