Sub topic 13
Heap Sort in Practice: The Introsort Fallback
Heap sort has a guaranteed O(n log n) worst case and needs only O(1) extra space. Even so, few standard libraries use it as their main sort. Its most common job in production code is as a safety net. This chapter shows how introsort uses heap sort to keep quicksort's speed while removing quicksort's O(n²) worst case.
This chapter assumes you already know the following from earlier chapters:
- how
sift_downand in-place heap sort work - the complexity comparison between heap sort, quicksort and merge sort
- what partitioning means in quicksort, and why a bad pivot sequence leads to O(n²)
The Problem Introsort Solves
On typical inputs, quicksort is usually the fastest comparison sort. It scans memory sequentially, so it uses the cache well. Its inner loop is short, and it sorts in place. Its weakness is that a run of bad pivots can make the recursion n levels deep, which costs O(n²) time and O(n) stack space. Median-of-three pivot selection makes this unlikely on sorted or reverse-sorted input. It does not rule it out. Inputs can be crafted to defeat it, and some simple partition schemes degrade on inputs with many duplicate keys.
David Musser published introsort ("introspective sort") in 1997. The idea is that the sort watches its own recursion depth. When the depth passes a limit proportional to log n, the sort concludes that quicksort is going badly on the current subarray. It then sorts that subarray with heap sort.
The Three Algorithms Inside Introsort
Introsort combines three sorts. Each one covers a weakness of the others.
| Component | When it runs | Why it is there |
|---|---|---|
| Quicksort partitioning | Normal case, depth budget remaining | Fastest on typical data and cache-friendly |
| Heap sort | Depth budget used up on a subarray | O(n log n) worst case with O(1) extra space |
| Insertion sort | Subarray smaller than a threshold (often 16) | Lowest overhead on tiny ranges |
Why Heap Sort Is the Fallback
Merge sort also guarantees O(n log n), so it might seem like an equally good fallback. In this role, heap sort wins on several points:
- Memory. Heap sort runs in place. Merge sort on arrays needs O(n) extra buffer space. A fallback that allocates memory could fail exactly when the input is large and hostile.
- Same contract. Introsort is already unstable because quicksort partitioning reorders equal keys. Heap sort's instability therefore loses nothing. Merge sort's stability would add nothing, because the overall sort still is not stable.
- Works on any subrange. Heap sort needs nothing beyond the slice
a[lo:hi]and index arithmetic offset bylo.
Heap sort's usual drawbacks are poor cache locality and roughly twice as many comparisons as quicksort on average. These matter little here, because the fallback rarely runs. On random data, it often never runs at all.
A Complete Introsort in Python
The implementation below follows the classic design. It uses a depth limit of 2·⌊log₂ n⌋, median-of-three pivot selection, an insertion sort threshold of 16, and heap sort on subranges. It also counts how many times the fallback runs, so you can see when it triggers.
import random
THRESHOLD = 16
fallbacks = 0
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 sift_down_range(a, lo, start, end):
# Heap occupies a[lo:lo+end]; indices start/end are relative to lo.
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[lo + child + 1] > a[lo + child]:
child += 1
if a[lo + root] >= a[lo + child]:
break
a[lo + root], a[lo + child] = a[lo + child], a[lo + root]
root = child
def heap_sort_range(a, lo, hi):
n = hi - lo
for start in range(n // 2 - 1, -1, -1):
sift_down_range(a, lo, start, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
sift_down_range(a, lo, 0, end)
def partition(a, lo, hi):
# Median-of-three: order a[lo], a[mid], a[hi-1], use the median as pivot.
mid = (lo + hi - 1) // 2
if a[mid] < a[lo]:
a[mid], a[lo] = a[lo], a[mid]
if a[hi - 1] < a[lo]:
a[hi - 1], a[lo] = a[lo], a[hi - 1]
if a[hi - 1] < a[mid]:
a[hi - 1], a[mid] = a[mid], a[hi - 1]
a[mid], a[hi - 1] = a[hi - 1], a[mid]
pivot = a[hi - 1]
i = lo
for j in range(lo, hi - 1):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi - 1] = a[hi - 1], a[i]
return i
def _introsort(a, lo, hi, depth):
global fallbacks
while hi - lo > THRESHOLD:
if depth == 0:
fallbacks += 1
heap_sort_range(a, lo, hi)
return
depth -= 1
p = partition(a, lo, hi)
# Recurse on the smaller side, loop on the larger side.
if p - lo < hi - p - 1:
_introsort(a, lo, p, depth)
lo = p + 1
else:
_introsort(a, p + 1, hi, depth)
hi = p
insertion_sort(a, lo, hi)
def introsort(a):
if len(a) < 2:
return
max_depth = 2 * (len(a).bit_length() - 1) # 2 * floor(log2 n)
_introsort(a, 0, len(a), max_depth)
def run(name, data):
global fallbacks
fallbacks = 0
expected = sorted(data)
introsort(data)
assert data == expected
print(f"{name:10} sorted correctly, heap sort fallbacks: {fallbacks}")
random.seed(1)
run("random", [random.randint(0, 10**6) for _ in range(1000)])
run("sorted", list(range(1000)))
run("reversed", list(range(1000, 0, -1)))
run("all equal", [7] * 1000) # fallbacks: 1The all-equal input is the interesting case. This partition uses the Lomuto scheme, which sends every element equal to the pivot to the right side. With all keys equal, each partition peels off one element, so plain quicksort would take O(n²) time. Introsort spends its 18-level depth budget (2·⌊log₂ 1000⌋ = 18) and then hands the remaining 982 elements to heap sort. The sort finishes in O(n log n) anyway. On the random, sorted and reversed inputs, median-of-three keeps partitions balanced, so the fallback seldom or never runs.
Details in the code that matter
heap_sort_rangeuses offsets. The heap formulas2*i + 1and2*i + 2assume the heap starts at index 0. The code computes indices relative to the subarray and addsloonly when it touchesa. If you write2*i + 1with absolute indices for a subarray that does not start at 0, you get a wrong heap that may look correct on small tests.- The depth counter belongs to each path. Each recursive call receives its own copy of
depth. One bad branch can exhaust its budget without affecting a healthy sibling. - Smaller-side recursion bounds the stack. The code recurses only into the smaller part and loops on the larger part, so the stack never grows past O(log n) frames. The depth limit bounds time, and this trick bounds space. They solve different problems.
>=insift_down_rangestops early on ties. Without it, equal keys trigger pointless swaps. The result stays correct, but the fallback does extra work.
Why the Worst Case Is O(n log n)
The argument has three parts:
- Partitioning. On any single recursion path, at most 2·⌊log₂ n⌋ partition levels happen. The subarrays at any one level are disjoint, so each level does O(n) total partition work. The total is O(n log n).
- Heap sort calls. Every fallback runs on a disjoint subarray of size mᵢ, and the mᵢ sum to at most n. Each call costs O(mᵢ log mᵢ) ≤ O(mᵢ log n), so all of them together cost O(n log n).
- Insertion sort. Each small range has at most 16 elements, so it costs O(16²). There are O(n/16) such ranges after partitioning, which totals O(n).
Adding the three parts gives O(n log n) in the worst case. On typical input the run time is close to quicksort's, because parts 2 and 3 are small.
Where You Meet It
| Library | Sort | Role of heap sort |
|---|---|---|
| C++ `std::sort` (libstdc++, libc++) | Introsort | Fallback when the depth limit is reached |
| .NET `Array.Sort` (since .NET Framework 4.5) | Introsort | Fallback when the depth limit is reached |
| Go `sort.Sort` / `slices.Sort` (since Go 1.19) | Pattern-defeating quicksort (pdqsort) | Fallback after too many unbalanced partitions |
| Rust `slice::sort_unstable` | pdqsort-derived quicksort | Fallback for guaranteed O(n log n) |
| Java `Arrays.sort` for primitives (JDK 14+) | Dual-pivot quicksort | Fallback when recursion is too deep |
Python's list.sort is missing from the table because it uses a stable merge-based algorithm (Timsort, and Powersort since 3.11), so heap sort plays no part in it. pdqsort changes the trigger. It counts badly unbalanced partitions instead of raw depth, and it shuffles some elements before giving up. The fallback is still heap sort, for the reasons given earlier.
Common Mistakes When Writing Introsort
- Computing the depth limit once per call instead of once overall. If you recompute
2*log2(size)for every subarray, the budget never runs out, and the fallback never fires. - Falling back to the whole array. Calling heap sort on
ainstead ofa[lo:hi]discards finished work. Worse, it may sort across subarray boundaries that partitioning has already settled. The result is still correct, but you lose the speed benefit. - Using a slice copy.
heap_sort(a[lo:hi])in Python sorts a copy and leavesaunchanged. The fallback must work in place through offsets. - Forgetting the final small-range sort. If the loop exits at the threshold and nothing sorts the remaining ranges, the output is only partially sorted.
Exercise
For an array of 1,000,000 elements, what depth budget does this chapter's introsort assign, and how many elements can a single heap sort fallback receive at most if each partition on that path peels off only the pivot?
Show answer
floor(log2 1,000,000) = 19, so the budget is 2 * 19 = 38 levels. Each degenerate partition removes one element (the pivot), so after 38 levels the remaining subarray has 1,000,000 - 38 = 999,962 elements, and heap sort sorts all of them. The run still finishes in O(n log n).
Exercise
Someone proposes merge sort instead of heap sort as the fallback because merge sort makes fewer comparisons. Give two reasons this is a poor fit for std::sort-style introsort.
Show answer
First, array merge sort needs O(n) extra memory, which breaks introsort's in-place, O(log n) auxiliary space guarantee and can fail to allocate. Second, its stability brings no benefit, because the quicksort phase has already reordered equal keys and the overall sort cannot be stable. Fewer comparisons in a path that seldom runs do not make up for these costs.
Exercise
Change the partition function so that elements equal to the pivot are split evenly between both sides (for example, by using Hoare partitioning). What happens to the fallback count for the all-equal input, and why?
Show answer
It drops to 0. With equal keys split between both sides, each partition divides the subarray roughly in half, so the recursion depth stays near log2 n, well under the 2 * log2 n budget. The fallback triggers only when partitions are unbalanced, and how balanced they are depends on how the partition handles duplicates.