Sub topic 13
Bounding Recursion Depth
This chapter assumes you know the Lomuto partition and recursive quicksort from earlier chapters. It also assumes you understand how the call stack grows with each recursive call, and that you know why sorted input makes a last-element pivot go quadratic.
The Problem: Stack Depth, Not Just Time
The plain recursive quicksort makes two recursive calls per partition. When the partitions are badly unbalanced, one side holds n − 1 elements and the other holds none. The recursion then goes n levels deep, and every level keeps a stack frame alive.
That is a separate problem from the O(n²) running time. A slow sort still finishes. A sort that runs out of stack crashes. Python's default recursion limit is 1000, so a sorted list of a few thousand elements is enough to raise RecursionError. In C, the same situation can overflow the thread's stack and kill the process.
The Fix: Recurse on the Smaller Side, Loop on the Larger
The second recursive call in quicksort is a tail call, meaning nothing happens after it returns. A tail call can be replaced by updating lo or hi and looping. Some compilers perform this tail-call elimination automatically. Python never does, so you write the loop yourself.
Which side you loop on matters. If you always recurse on the smaller partition and loop on the larger one, each recursive call gets at most half of the current range. A range can only be halved about log₂ n times, so the stack depth is at most O(log n).
Measuring the Difference
The script below runs both versions on sorted input, which is the worst case for a last-element pivot. Each version records the deepest active call.
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def quicksort_naive(a, lo, hi, depth, stats):
if lo < hi:
stats["max"] = max(stats["max"], depth)
p = lomuto_partition(a, lo, hi)
quicksort_naive(a, lo, p - 1, depth + 1, stats)
quicksort_naive(a, p + 1, hi, depth + 1, stats)
def quicksort_bounded(a, lo, hi, depth, stats):
while lo < hi:
stats["max"] = max(stats["max"], depth)
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
quicksort_bounded(a, lo, p - 1, depth + 1, stats)
lo = p + 1
else:
quicksort_bounded(a, p + 1, hi, depth + 1, stats)
hi = p - 1
n = 500
for sorter in (quicksort_naive, quicksort_bounded):
data = list(range(n))
stats = {"max": 0}
sorter(data, 0, n - 1, 1, stats)
assert data == sorted(data)
print(sorter.__name__, "max depth:", stats["max"])
# quicksort_naive max depth: 499
# quicksort_bounded max depth: 1On sorted input, every partition puts the pivot at hi, so the right side is empty. The bounded version "recurses" into that empty range, which returns at once, and then loops on the large side. Try n = 5000: the naive version raises RecursionError, and the bounded one still finishes.
Common Mistakes
| Mistake | Consequence |
|---|---|
| Always looping on the right side | Depth is still O(n) when the left side is the large one |
| Forgetting to update `lo`/`hi` after the recursive call | Infinite loop |
| Applying this to Hoare's scheme with `p - 1` bounds | Elements are skipped; Hoare's ranges are `lo..p` and `p+1..hi` |
Exercise
Why does recursing on the smaller partition guarantee O(log n) stack depth, even when the partitions are badly unbalanced?
Show answer
The pivot is excluded from both sides, so the smaller side has at most (size − 1) / 2 elements, less than half the current range. Each new stack frame therefore covers less than half the range of its caller. After about log₂ n nested calls the range has at most one element and the recursion stops. The larger side is handled by the loop inside the same frame, so it adds no depth.
Exercise
Adapt quicksort_bounded to Hoare's partition scheme. Which comparison and which updates change?
Show answer
Hoare's ranges are lo..p and p+1..hi. Compare p - lo + 1 with hi - p. If the left is smaller, recurse on (lo, p) and set lo = p + 1. Otherwise recurse on (p + 1, hi) and set hi = p.