Sub topic 18
Divide and Conquer in Practice: Cutoffs, Stack Depth, and Parallelism
This chapter assumes you have already worked through merge sort and quicksort, can read recursive Python, and know Big-O notation. The analysis so far has counted operations asymptotically. Real programs also pay for function calls, have a limited call stack, and run on machines with several cores. Each of these three facts leads to a change in how you write a divide-and-conquer algorithm.
Small-Input Cutoffs
A recursive call costs time for creating a stack frame, slicing or passing bounds, and returning. Near the leaves of the recursion tree, the subproblems are tiny, and this overhead outweighs the work being done. Insertion sort runs in O(n²), but on 10 to 30 elements it beats merge sort because its inner loop is simple. A hybrid algorithm stops recursing below a cutoff and switches to the simpler method.
import heapq
import random
CUTOFF = 16
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi):
x = a[i]
j = i - 1
while j >= lo and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def hybrid_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a)
if hi - lo <= CUTOFF:
insertion_sort(a, lo, hi)
return
mid = (lo + hi) // 2
hybrid_sort(a, lo, mid)
hybrid_sort(a, mid, hi)
a[lo:hi] = list(heapq.merge(a[lo:mid], a[mid:hi]))
data = [random.randint(0, 999) for _ in range(1000)]
hybrid_sort(data)
print(data == sorted(data)) # TrueThe asymptotic bound stays O(n log n). The cutoff only removes the bottom few levels of the tree, where most of the calls happen. Python's built-in sort (Timsort) uses the same idea: it applies binary insertion sort to short runs.
Controlling Recursion Depth
CPython's default recursion limit is about 1000 frames. Merge sort's depth is log₂ n, so the limit is never a problem. Quicksort's depth can grow to n when the pivots are bad, and a call stack that deep raises RecursionError. The fix is to recurse only into the smaller partition and to handle the larger one with a loop. The smaller side holds at most half the elements, so the stack depth is O(log n) for any choice of pivots.
import random
def partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
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
while lo < hi:
p = partition(a, lo, hi)
if p - lo < hi - p:
quicksort(a, lo, p - 1)
lo = p + 1
else:
quicksort(a, p + 1, hi)
hi = p - 1
nums = list(range(20000))
quicksort(nums)
print(nums == sorted(nums)) # TrueParallelism
When subproblems are independent, as in merge sort, they can run on separate cores. The combine step still runs on one core and is often the bottleneck. In CPython, threads do not speed up CPU-bound work because of the global interpreter lock (GIL), so use processes instead.
from concurrent.futures import ProcessPoolExecutor
import heapq
import random
def parallel_sort(a, workers=4):
size = max(1, (len(a) + workers - 1) // workers)
chunks = [a[i:i + size] for i in range(0, len(a), size)]
with ProcessPoolExecutor(max_workers=workers) as ex:
sorted_chunks = list(ex.map(sorted, chunks))
return list(heapq.merge(*sorted_chunks))
if __name__ == "__main__":
data = [random.random() for _ in range(1_000_000)]
print(parallel_sort(data) == sorted(data)) # TrueSplit only at the top level. Sending data between processes is expensive, so starting a new process for every small subproblem costs more than it saves.
| Concern | Symptom | Remedy |
|---|---|---|
| Call overhead | Slow on many small subproblems | Cutoff to a simple base algorithm |
| Stack depth | `RecursionError` on adversarial input | Recurse on the smaller side, loop on the larger |
| Idle cores | One CPU busy | Run top-level subproblems in separate processes |
Exercise
A quicksort always recurses on the left partition first and then on the right one, with no loop. Given an already sorted list of 5000 elements and a pivot that is always the last element, what happens in CPython, and what one change fixes it without changing the pivot rule?
Show answer
Every partition leaves n−1 elements on one side, so the recursion depth reaches about 5000 and exceeds the default limit of about 1000, raising RecursionError. Recurse only into the smaller partition and handle the larger one with a while loop. The depth then stays at most log₂ n, although the running time is still O(n²).
Exercise
Why does adding a cutoff of 16 not change merge sort's O(n log n) bound?
Show answer
Insertion sort on a block of at most 16 elements costs O(1) per block. There are about n/16 blocks, so the leaves cost O(n) in total, and the remaining log(n/16) levels still cost O(n) each.