Sub topic 2
Base Cases and Why Recursion Terminates
This chapter assumes you can write and trace recursive functions in Python and read Big-O notation. Every divide-and-conquer algorithm needs two things to stop: a base case, and a guarantee that each recursive call moves toward it.
What a Base Case Does
A base case is an input small enough to solve directly, without recursing. In merge sort, a list of length 0 or 1 is already sorted. In exponentiation by squaring, x ** 0 is 1. The base case is where the recursion stops and the combine steps start returning values back up.
A base case alone does not guarantee that the recursion stops. It must also be reachable from every input.
The Termination Argument
To show that a recursive algorithm terminates, pick a measure, usually the input size n, that has two properties:
- Every recursive call is made on a strictly smaller measure.
- The measure cannot shrink forever. Sizes are non-negative integers, so they eventually hit the base case.
For divide and conquer, check this at the boundary. Take the smallest input that is not a base case and confirm that each subproblem it creates is smaller than it is. Off-by-one errors show up there.
A Base Case That Is Too Small
This merge sort only treats the empty list as a base case:
import heapq
def bad_sort(a):
if len(a) == 0:
return a
mid = len(a) // 2
return list(heapq.merge(bad_sort(a[:mid]), bad_sort(a[mid:])))
def good_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
return list(heapq.merge(good_sort(a[:mid]), good_sort(a[mid:])))
print(good_sort([5, 2, 9, 1])) # [1, 2, 5, 9]
try:
bad_sort([5, 2, 9, 1])
except RecursionError:
print("bad_sort never reached its base case")For a list of length 1, mid is 0, so a[mid:] is the same one-element list. The measure did not decrease, so the recursion never ends. In Python it stops with a RecursionError once the stack reaches about 1000 frames.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Base case misses size 1 | Infinite recursion on singletons | Use `len(a) <= 1` |
| Split leaves one side the full size | Measure does not shrink | Check that `mid` divides sizes 2 and 1 correctly |
| Empty input not handled | Index error or wrong result on `[]` | Make the base case cover `n == 0` |
| Pivot kept in a recursive side | Recursion loops on repeated values | Exclude the pivot or the elements equal to it |
Exercise
A quickselect variant builds lows = [x for x in a if x <= pivot] and recurses into lows when k < len(lows). Why might it never terminate, and which input shows the problem?
Show answer
When every element equals the pivot, lows is the whole list, so the recursive call gets an input of the same size and the measure never decreases. The input [4, 4, 4] with k = 0 recurses forever. Keeping only x < pivot in lows and handling elements equal to the pivot separately makes every recursive call strictly smaller.