Sub topic 18
Divide and Conquer in Practice: Cutoffs, Stack Depth, and Parallelism
Earlier chapters judged algorithms by their asymptotic bounds. Real programs also pay for function calls, use stack memory for each pending recursion, and run on machines with several cores. This chapter covers three practical adjustments: small-input cutoffs, keeping recursion depth bounded, and splitting independent subproblems across processors.
This chapter assumes you have read the merge sort and quicksort chapters, can read Python, and know Big-O notation. You should also know what a call stack is: the memory region that holds one frame for each active function call.
Small-Input Cutoffs
Why the base case is too small
Textbook merge sort recurses down to lists of length 1. Near the leaves, the recursion costs more than the useful work it does. Every call allocates a frame, slices or indexes, and returns. Half of all calls in merge sort happen on inputs of size 1, and a quarter happen on inputs of size 2.
Insertion sort is O(n²), but its constant factors are tiny and it runs fast on short or nearly sorted ranges. A hybrid algorithm stops recursing below a threshold, called the cutoff, and hands the small range to the simpler algorithm. The asymptotic bound stays O(n log n): the leaves now cost O(k²) each for cutoff k, and there are n/k of them, giving O(nk) extra work, which is O(n) for a constant k.
A hybrid merge sort
This version also allocates one auxiliary buffer up front instead of creating new lists at every level, and it skips the merge when the two halves are already in order.
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 _sort(a, buf, lo, hi):
if hi - lo <= CUTOFF:
insertion_sort(a, lo, hi)
return
mid = (lo + hi) // 2
_sort(a, buf, lo, mid)
_sort(a, buf, mid, hi)
if a[mid - 1] <= a[mid]:
return # halves already in order
buf[lo:hi] = a[lo:hi]
i, j = lo, mid
for k in range(lo, hi):
if i < mid and (j >= hi or buf[i] <= buf[j]):
a[k] = buf[i]
i += 1
else:
a[k] = buf[j]
j += 1
def hybrid_merge_sort(a):
buf = a[:]
_sort(a, buf, 0, len(a))
return a
data = [random.randint(0, 1000) for _ in range(10_000)]
print(hybrid_merge_sort(data[:]) == sorted(data)) # TrueThe buf[i] <= buf[j] comparison takes from the left half on ties, which keeps the sort stable.
Controlling Recursion Depth
The failure mode
Each pending call holds a stack frame. CPython limits recursion depth (by default sys.getrecursionlimit() returns 1000) and raises RecursionError beyond it. Compiled languages have no such counter, but they crash when the stack overflows.
Merge sort always splits evenly, so its depth is about log₂ n. That is 20 levels for a million elements, which is safe. Quicksort is the risky one. With a bad pivot sequence, such as the first element as pivot on already sorted input, each call peels off one element and the depth reaches n.
Recurse on the smaller side, loop on the larger
The fix is to make a recursive call only for the smaller partition and handle the larger one by updating the bounds and looping. The recursive call always gets at most half the current range, so the depth is at most log₂ n no matter how bad the pivots are.
import random
import sys
def partition(a, lo, hi):
# Lomuto partition of a[lo:hi] around a random pivot; returns the pivot's final index
p = random.randrange(lo, hi)
a[p], a[hi - 1] = a[hi - 1], a[p]
pivot = a[hi - 1]
store = lo
for i in range(lo, hi - 1):
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi - 1] = a[hi - 1], a[store]
return store
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a)
while hi - lo > 1:
p = partition(a, lo, hi)
if p - lo < hi - p - 1:
quicksort(a, lo, p) # smaller side: recurse
lo = p + 1 # larger side: loop
else:
quicksort(a, p + 1, hi)
hi = p
return a
print(sys.getrecursionlimit()) # usually 1000
data = list(range(200_000))
print(quicksort(data[:]) == data) # TrueRaising the limit with sys.setrecursionlimit hides the symptom without fixing the cause. A deep enough recursion can still overflow the interpreter's own C stack and crash the process. Introsort, used by many C++ standard libraries, goes further: it tracks depth and switches to heapsort once the depth passes about 2 log₂ n, which guarantees O(n log n) worst-case time.
Parallelism
Independent subproblems
The subproblems in divide and conquer usually touch disjoint data, so they can run at the same time. Two measures describe the gain:
- Work is the total number of operations, the same as the sequential running time.
- Span is the length of the longest chain of steps that must happen in order, which is the running time with unlimited processors.
For merge sort with a sequential merge, the work is O(n log n). The span satisfies S(n) = S(n/2) + O(n) = O(n), because the top-level merge alone touches all n elements. The best possible speedup is therefore work divided by span, O(log n). Parallel merge algorithms reduce the span further, but they are more complex.
Coarse-grained splitting in Python
In standard CPython, the global interpreter lock stops threads from running Python bytecode in parallel, so CPU-bound work needs processes. Sending data to a process means pickling it, and that is expensive. The practical pattern is to split once into one chunk per worker, sort the chunks in parallel, and merge the results in the parent.
import heapq
import random
from concurrent.futures import ProcessPoolExecutor
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 pool:
sorted_chunks = list(pool.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)) # TrueThe if __name__ == "__main__": guard is required on platforms that start worker processes by re-importing the module, such as Windows and macOS. The parallel cutoff applies the same idea as the sequential cutoff: start a new task only while the subproblem is large enough to cover the cost of scheduling it. If you start one task per recursive call, the overhead outweighs the speedup.
Summary of Concerns
| Concern | Symptom | Fix |
|---|---|---|
| Call overhead at leaves | Slow on small inputs despite good Big-O | Cutoff to insertion sort |
| Repeated allocation | High memory churn from slicing | One preallocated buffer, index ranges |
| Deep recursion | RecursionError or stack overflow | Recurse on smaller side, loop on larger; introsort depth limit |
| Equal keys in quicksort | O(n²) time | Three-way partition |
| Parallel overhead | Parallel version slower than sequential | Split coarsely; spawn tasks only above a size threshold |
| Large span | Speedup stalls as cores increase | Parallelize the combine step |
Exercise
With a cutoff of k, a hybrid merge sort stops recursing on ranges of size at most k and insertion-sorts them. Show that the total time is O(nk + n log(n/k)), and explain why this is still O(n log n) for constant k.
Show answer
There are about n/k leaves, each costing O(k²) for insertion sort, which totals O(nk). The recursion above the leaves has about log₂(n/k) levels, and each level does O(n) merging work, which totals O(n log(n/k)). For constant k, O(nk) is O(n) and O(n log(n/k)) is O(n log n), so the sum is O(n log n).
Exercise
In the quicksort above, suppose every partition puts the pivot at index lo, leaving all other elements on the right. What is the maximum recursion depth, and what is the running time?
Show answer
The left side is empty, so it is the smaller side. Recursing on it returns at once, and the loop continues with lo = p + 1. The depth never exceeds 2, but the loop runs n times with O(n) partitions, so the time is O(n²). The technique bounds depth, not time.
Exercise
Why does parallel_sort split the data into exactly one chunk per worker instead of recursively spawning a process for every half down to small sizes?
Show answer
Each task sent to a process requires pickling its input and output, which costs time proportional to the data size plus a fixed scheduling cost. Fine-grained tasks multiply that overhead without adding usable parallelism, since only workers tasks can run at once. One chunk per worker pays the transfer cost once per element and keeps every core busy.