Sub topic 14
Switching to Insertion Sort for Small Subarrays
This chapter assumes you know the recursive quicksort from earlier chapters, the lomuto_partition function, how insertion sort works, and basic Big-O reasoning. The question here is practical. Quicksort is fast on large arrays, but most of its recursive calls handle tiny subarrays. Is quicksort still the right tool once a subarray has shrunk to a handful of elements?
Why Small Subarrays Are Expensive
Picture the recursion tree of quicksort on a random array of size n. Each partition splits a range in two, so the bottom levels of the tree hold a very large number of tiny ranges: sizes 0, 1, 2, 3. A plain quicksort makes about n recursive calls in total, and most of them sit at these bottom levels.
Every call costs more than its comparisons. It pushes a stack frame, evaluates lo < hi, runs the partition loop setup, swaps the pivot, and returns. When a range holds three elements, this fixed overhead is far larger than the useful work.
Insertion sort behaves the opposite way. Its average cost is about n²/4 comparisons, which is terrible for large n. For small n it has very low constant factors:
- It makes no function calls and uses no extra stack.
- Its inner loop is a single compare-and-shift over adjacent memory, which caches well.
- It runs in linear time on input that is already nearly sorted.
Both algorithms make a few comparisons on a 10-element array. Insertion sort skips the bookkeeping, so it wins at that size. The standard fix follows from this: when a subarray's size drops to a cutoff M or below, stop recursing and insertion-sort it.
Variant 1: Sort Each Small Subarray Immediately
The simplest version replaces the base case. The size test is hi - lo + 1 <= cutoff. An empty range has hi < lo, and insertion sort handles it because its loop range is empty.
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 randomized_partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
return lomuto_partition(a, lo, hi)
def insertion_sort(a, lo, hi):
"""Sort a[lo..hi] inclusive, never looking left of lo."""
for i in range(lo + 1, hi + 1):
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 quicksort_cutoff(a, lo=0, hi=None, cutoff=16):
if hi is None:
hi = len(a) - 1
if hi - lo + 1 <= cutoff:
insertion_sort(a, lo, hi)
return
p = randomized_partition(a, lo, hi)
quicksort_cutoff(a, lo, p - 1, cutoff)
quicksort_cutoff(a, p + 1, hi, cutoff)
data = [random.randint(0, 99) for _ in range(1000)]
quicksort_cutoff(data)
print(data == sorted(data)) # TrueThe j >= lo guard is important. Without it, insertion sort walks into elements that belong to other subarrays. In this variant the result would still come out sorted, because everything left of lo is already no larger than the elements in the range. But each call would then do more work than its own range needs, and the code would only be correct because of an unstated invariant.
Variant 2: One Final Insertion Sort Pass
Robert Sedgewick described an alternative. Small subarrays are left unsorted during the recursion. After the recursion finishes, a single insertion sort runs over the whole array.
def _quicksort_coarse(a, lo, hi, cutoff):
if hi - lo + 1 <= cutoff:
return # leave this block unsorted for now
p = randomized_partition(a, lo, hi)
_quicksort_coarse(a, lo, p - 1, cutoff)
_quicksort_coarse(a, p + 1, hi, cutoff)
def quicksort_final_pass(a, cutoff=16):
_quicksort_coarse(a, 0, len(a) - 1, cutoff)
insertion_sort(a, 0, len(a) - 1)
data = [random.randint(0, 99) for _ in range(1000)]
quicksort_final_pass(data)
print(data == sorted(data)) # TrueRunning insertion sort over n elements sounds quadratic. It is not, and the reason is worth working through. After the coarse phase, the array is a sequence of unsorted blocks, each with at most M elements. The blocks are separated by pivots already in their final places. Every element in a block is at least as large as everything before the block. When insertion sort shifts an element left, the a[j] > x test fails at or before the block's left edge. Each element therefore moves fewer than M positions, so the final pass costs O(nM). With M fixed, that is O(n).
Choosing Between the Variants
| Aspect | Sort each block immediately | Single final pass |
|---|---|---|
| Insertion sort calls | One per small block, about n/M | One in total |
| Cache behavior | Block is still in cache from the partition that produced it | Second sweep over the whole array, which may have left cache |
| Code complexity | Base case changes only | Needs a separate final step that is easy to forget |
| Correctness depends on | Each block's own bounds | The invariant that blocks are separated by pivots |
| Used by | Many modern implementations | GCC's libstdc++ `std::sort` (threshold 16) |
On machines from before deep cache hierarchies, the final pass saved call overhead. On current hardware the two variants usually perform within a few percent of each other. Variant 1 is the safer default because each block is sorted while it is still hot in cache, and its correctness depends on nothing beyond the block itself.
How the Cutoff Changes the Analysis
The cutoff cuts off the bottom of the recursion tree. A random-pivot recursion tree has depth around 2 ln n on average. Stopping at size M removes roughly the bottom log₂ M levels, and those levels are where nearly all the calls happen. The number of recursive calls falls from about n to the order of n/M.
The asymptotic picture does not change:
- Average case: still O(n log n). The insertion sort work is O(n/M · M²) = O(nM), a linear term for fixed M.
- Worst case: still O(n²). A cutoff does nothing about bad pivots. Randomization, median-of-three, and introsort (next chapter) handle that.
- Stability: still unstable. Insertion sort is stable, but partitioning has already reordered equal keys before the blocks reach it.
The cutoff is a constant-factor optimization. In compiled languages it typically saves 10–20% of running time, which is large enough that every serious library uses it.
Picking M
The best M depends on the cost of a function call relative to a compare-and-shift. Textbooks usually suggest something between 5 and 20. Libraries pick values from benchmarks: libstdc++ uses 16, and Java's DualPivotQuicksort in JDK 7 and 8 used 47 for primitive arrays. Too small an M leaves most of the call overhead in place. Too large an M lets insertion sort's quadratic term take over.
Measure rather than guess. The script below counts recursive calls and times several cutoffs on the same input. It uses the functions defined above.
import random
import time
calls = 0
def quicksort_counted(a, lo, hi, cutoff):
global calls
calls += 1
if hi - lo + 1 <= cutoff:
insertion_sort(a, lo, hi)
return
p = randomized_partition(a, lo, hi)
quicksort_counted(a, lo, p - 1, cutoff)
quicksort_counted(a, p + 1, hi, cutoff)
random.seed(42)
base = [random.random() for _ in range(100_000)]
for m in [1, 4, 8, 16, 32, 64, 128]:
a = base[:]
calls = 0
t0 = time.perf_counter()
quicksort_counted(a, 0, len(a) - 1, m)
elapsed = time.perf_counter() - t0
assert a == sorted(base)
print(f"M={m:4d} calls={calls:7d} time={elapsed:.3f}s")The call count drops sharply as M grows, roughly in proportion to 1/M. The timings in CPython will show a flatter optimum than in C. Interpreter overhead slows insertion sort's inner loop as much as it slows a function call, so the best Python cutoff is not a guide for a C or Rust implementation.
Common Mistakes
- Sorting the whole array at each leaf. Calling
insertion_sort(a, 0, len(a) - 1)inside the base case turns the algorithm quadratic. - Off-by-one size test. The range
lo..hiholdshi - lo + 1elements. Writinghi - lo <= cutoffmakes the effective cutoff one larger than intended. That is harmless, but it skews benchmarks. - Forgetting the final pass in Variant 2. The output then looks almost sorted, and small tests with n ≤ M pass by accident because no partitioning happens.
- Expecting protection from worst cases. A sorted input with a fixed last-element pivot is still quadratic, whatever the cutoff.
Exercise
In the final-pass variant with cutoff M = 16, a student swaps the order of the final pass and the coarse phase, so insertion sort runs first and the coarse quicksort runs second. Is the output sorted, and what is the running time on a random array?
Show answer
The output is not guaranteed to be sorted. The coarse phase leaves blocks of up to 16 elements unsorted, and nothing sorts them afterwards. Partitioning also moves elements around, so the earlier insertion sort pass does not keep each block in order. The running time is also poor: the first insertion sort runs on a random array, which costs about n²/4 comparisons, so the total is O(n²).
Exercise
Explain why each element moves fewer than M positions during the final insertion sort pass, and state the total cost of that pass.
Show answer
After the coarse phase, the array consists of blocks of at most M elements, separated by pivots in their final positions. Every element of a block is at least as large as every element before the block. When insertion sort shifts an element left, the comparison a[j] > x fails at or before the block's left edge, so the element moves at most M − 1 positions. Over n elements the pass costs O(nM), which is O(n) for a fixed M.
Exercise
Adding a cutoff of M = 16 to a randomized quicksort makes it 15% faster on random data. Does it change the average-case or worst-case complexity? Does it make the sort stable?
Show answer
Neither complexity class changes. The average case stays O(n log n), because the cutoff adds only an O(nM) term and removes constant-factor overhead. The worst case stays O(n²), because bad pivots still produce unbalanced splits above the cutoff. The sort stays unstable: partitioning has already reordered equal keys before insertion sort sees the small blocks.