Sub topic 13
Bounding Recursion Depth
This chapter assumes you know the Lomuto partition scheme and the recursive quicksort built on it from earlier chapters. You should also know how the call stack works and why the worst-case running time is O(n²). The quicksort analysis so far has been about time. Here the subject is space: how many stack frames quicksort can have alive at once, and how to keep that number at O(log n) on every input.
Why Depth Is a Separate Problem
Each recursive call takes one stack frame. The frame holds its locals (a, lo, hi, p) and a return address. Frames for calls that have returned are freed, so memory use depends on the maximum number of frames alive at once, which is the recursion depth.
The plain recursive quicksort makes two calls after partitioning:
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(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)On sorted input with a last-element pivot, each partition peels off one element. The left call handles n − 1 elements, then n − 2, and so on, and each of those calls is still active while the next one runs. The depth reaches about n.
This matters in practice for two reasons:
- In Python, the default recursion limit is 1000 (
sys.getrecursionlimit()). Sorting 5,000 already-sorted integers with the code above raisesRecursionError. - In C, C++, or Rust, the stack has a fixed size, often 1–8 MB for the main thread and less for worker threads. Overflowing it crashes the process with no exception to catch.
Pivot randomization from earlier chapters makes deep recursion unlikely. It does not rule it out. A library sort cannot crash on an unlucky input or on input an attacker has crafted, so it needs a guarantee that holds for every input.
Step 1: Turn One Call Into a Loop
The second recursive call, quicksort(a, p + 1, hi), is the last thing the function does. That makes it a tail call: once it returns, the caller has no more work to do. A tail call can be replaced by reassigning the parameters and jumping back to the top of the function. This is tail-call elimination.
Python never does this for you. C and C++ compilers sometimes do at higher optimization levels, but the language does not require it, so you can't rely on it. You can do it by hand:
def quicksort_tail(a, lo, hi):
while lo < hi:
p = lomuto_partition(a, lo, hi)
quicksort_tail(a, lo, p - 1)
lo = p + 1This alone does not fix the problem. The loop handles the right side and the recursion still goes into the left side. On sorted input with a last-element pivot, the left side is the big one, so the depth is still about n. The left-side recursion is the part that grows deep, and that is exactly the part this version keeps.
Step 2: Recurse on the Smaller Side
The fix is to choose, after each partition, which side gets the recursive call: always the smaller one. The larger side is handled by the loop.
def quicksort_bounded(a, lo, hi):
while lo < hi:
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
quicksort_bounded(a, lo, p - 1)
lo = p + 1
else:
quicksort_bounded(a, p + 1, hi)
hi = p - 1The left side lo..p-1 has p - lo elements. The right side p+1..hi has hi - p elements. The comparison picks the smaller one for recursion, and the loop then narrows lo or hi to the larger one.
Why the Depth Is O(log n)
Take a range of m elements. Partitioning removes the pivot and leaves two sides whose sizes add up to m − 1. The smaller side has at most (m − 1) / 2 elements, which is less than m / 2.
Each new stack frame comes from a recursive call, and recursive calls only go to the smaller side. So the range size at least halves with each extra level of depth. The loop iterations inside one frame don't add frames. After d levels the range has fewer than n / 2^d elements. Once that falls below 2, the guard lo < hi stops further calls, so the depth is at most about log₂ n + 1.
For a million elements, that is about 21 frames, whatever the pivots are.
Notice what the argument leaves out. It says nothing about how good the pivot is. A terrible split such as (0, n − 1) puts a zero-size range on the recursive side, which returns at once, and the loop takes the n − 1 side. Bad pivots cost loop iterations, and loop iterations cost no stack space.
Measuring It
The script below instruments both versions to record the deepest frame reached. It runs as shown.
import math
import random
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 naive(a, lo, hi, depth, stats):
stats["max"] = max(stats["max"], depth)
if lo < hi:
p = lomuto_partition(a, lo, hi)
naive(a, lo, p - 1, depth + 1, stats)
naive(a, p + 1, hi, depth + 1, stats)
def bounded(a, lo, hi, depth, stats):
stats["max"] = max(stats["max"], depth)
while lo < hi:
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
bounded(a, lo, p - 1, depth + 1, stats)
lo = p + 1
else:
bounded(a, p + 1, hi, depth + 1, stats)
hi = p - 1
def max_depth(sorter, data):
a = list(data)
stats = {"max": 0}
sorter(a, 0, len(a) - 1, 1, stats)
assert a == sorted(data)
return stats["max"]
n = 800
sorted_input = list(range(n))
random_input = random.sample(range(n), n)
print("naive, sorted: ", max_depth(naive, sorted_input)) # 800
print("bounded, sorted:", max_depth(bounded, sorted_input)) # 2
d = max_depth(bounded, random_input)
print("bounded, random:", d)
assert d <= math.log2(n) + 1
big = list(range(3000))
try:
max_depth(naive, big)
except RecursionError:
print("naive, 3000 sorted: RecursionError")
print("bounded, 3000 sorted:", max_depth(bounded, big)) # 2The sorted-input case shows the difference clearly. The naive version needs one frame per element. The bounded version needs only 2, because every recursive call it makes is on an empty right side. The bounded run on 3,000 sorted elements still does about 4.5 million comparisons, which is the O(n²) time cost the callout warned about. It finishes, but slowly.
An Explicit-Stack Variant
Some codebases avoid recursion entirely, for example in kernels, embedded code, or languages with small default stacks. The same rule carries over to an explicit stack, but the roles swap: push the larger side to be handled later, and keep working on the smaller side right away.
def quicksort_iterative(a):
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
while lo < hi:
p = lomuto_partition(a, lo, hi)
if p - lo < hi - p:
stack.append((p + 1, hi))
hi = p - 1
else:
stack.append((lo, p - 1))
lo = p + 1Every entry pushed while the inner loop works on a range is pushed while that range is shrinking by at least half each time. So at most about log₂ n entries are on the stack at once. In C you can then allocate the stack as a fixed array of, say, 64 entries, which is enough for any array that fits in a 64-bit address space.
Comparing the Options
| Strategy | Worst-case stack depth | Worst-case time | Notes |
|---|---|---|---|
| Two recursive calls | O(n) | O(n²) | Fails on sorted input in Python beyond ~1000 elements |
| Loop on the right side, recurse on the left | O(n) | O(n²) | Removes the tail call but keeps the deep side recursive |
| Recurse on the smaller side, loop on the larger | O(log n) | O(n²) | Standard fix; adds one comparison per partition |
| Explicit stack, push larger, continue on smaller | O(log n) | O(n²) | Stack can be a fixed-size array |
The extra cost is a single integer comparison per partition, which is negligible next to the partition's linear scan. That is why practically every production quicksort uses one of the last two forms.
Edge Cases
- Equal sizes. When
p - lo == hi - p, either choice is fine. The code above recurses right. Either side is less than half the range, so the bound still holds. - All-equal keys with Lomuto.
a[j] < pivotis never true, sop == loevery time. The bounded version recurses on the empty left side and loops on the rest. Depth stays at 2, but time is O(n²). Three-way partitioning, covered in its own chapter, is the fix for the time. - Hoare partitioning. Hoare's scheme splits into
lo..pandp+1..hi, and neither side excludes a pivot. Comparep - lo + 1withhi - p. The pivot index(lo + hi) // 2keeps each side strictly smaller than the range, so the depth argument still applies.
Exercise
In quicksort_bounded, a partition of a 1,000-element range returns a split of 0 elements on the left and 999 on the right. How many new stack frames does this step create, and which range does the current frame work on next?
Show answer
It creates one new frame, for the empty left range, and that call returns immediately because lo >= hi. The current frame then sets lo = p + 1 and continues its loop on the 999-element right range without adding a frame.
Exercise
Write a depth-bounded version of quicksorthoare(a, lo, hi) that uses hoarepartition and recurses only on the smaller side.
Show answer
Compare the sizes p - lo + 1 and hi - p: def quicksorthoarebounded(a, lo, hi): while lo < hi: p = hoarepartition(a, lo, hi) if p - lo + 1 < hi - p: quicksorthoarebounded(a, lo, p) lo = p + 1 else: quicksorthoare_bounded(a, p + 1, hi) hi = p
Exercise
A colleague says that because quicksort_bounded limits the depth to O(log n), it is now safe against adversarial input. What is right and what is wrong about this claim?
Show answer
The claim is right that the stack cannot overflow, since the depth is at most about log2 n + 1 for every input. It is wrong about time. An adversary who can predict the pivots can still force O(n^2) comparisons, for example sorted input against a last-element pivot. Protecting the running time needs randomized pivots or an introsort-style fallback to heapsort.