Sub topic 13
Heap Sort in Practice: The Introsort Fallback
This chapter assumes you can already implement in-place heap sort and know its O(n log n) worst-case bound. It also assumes you know how quicksort partitions an array and why a poor pivot choice can push it to O(n²).
Heap sort is rarely the first algorithm a standard library runs. It is often the last one, the guarantee a library reaches for when its faster primary sort starts to go wrong. That pattern is called introsort (introspective sort). David Musser introduced it in 1997.
The problem introsort solves
Quicksort is usually the fastest comparison sort in practice. Its inner loop is tight, and it reads memory sequentially, which suits CPU caches. Its weakness is the worst case. If the pivots keep splitting the array badly, the recursion depth grows to about n and the running time grows to O(n²). Adversarial or unlucky inputs can cause this.
Heap sort has the opposite profile. It is O(n log n) on every input and needs O(1) extra space. Its access pattern jumps around the array, though, so its constant factors are usually worse than quicksort's.
Introsort combines the two. It runs quicksort, watches the recursion depth, and switches to heap sort on any subarray where the depth passes a limit. The usual limit is about 2·⌊log₂ n⌋. Small subarrays go to insertion sort, which is fastest on a handful of elements.
A working introsort
The heap sort below works on the slice a[lo:hi] in place. It does this by adding an offset lo to every index.
SMALL = 16
stats = {"heap_fallbacks": 0}
def _sift(a, lo, root, end):
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 heapsort_range(a, lo, hi):
n = hi - lo
for s in range(n // 2 - 1, -1, -1):
_sift(a, lo, s, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
_sift(a, lo, 0, end)
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 partition(a, lo, hi):
pivot = a[hi - 1] # naive pivot, on purpose
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):
while hi - lo > SMALL:
if depth == 0:
stats["heap_fallbacks"] += 1
heapsort_range(a, lo, hi)
return
depth -= 1
p = partition(a, lo, hi)
_introsort(a, p + 1, hi, depth)
hi = p # loop on the left side
insertion_sort(a, lo, hi)
def introsort(a):
_introsort(a, 0, len(a), 2 * (len(a).bit_length() - 1))
import random
data = [random.randint(0, 999) for _ in range(1000)]
introsort(data)
print(data == sorted(data)) # True
already_sorted = list(range(1000))
stats["heap_fallbacks"] = 0
introsort(already_sorted)
print(already_sorted == list(range(1000)), stats["heap_fallbacks"]) # True 1The last-element pivot makes sorted input a worst case for plain quicksort. Each partition removes only the pivot. After 18 wasted partitions (2·⌊log₂ 1000⌋), the depth budget runs out and heap sort finishes the remaining 982 elements in O(n log n).
Where you meet it
| Library | Primary sort | Heap sort role |
|---|---|---|
| C++ `std::sort` (libstdc++, libc++) | Introsort | Depth-limit fallback |
| .NET `Array.Sort` | Introsort | Depth-limit fallback |
| Go `sort.Sort`, Rust `sort_unstable` | Pattern-defeating quicksort | Fallback when partitions stay unbalanced |
These are all unstable sorts. That matches heap sort, which is not stable either. Stable library sorts such as Python's sorted use merge-based algorithms like Timsort instead.
Exercise
Why does introsort keep its O(n log n) worst-case bound even though quicksort can be O(n²)? Consider the work done before the fallback and the work done by heap sort.
Show answer
Quicksort recursion is cut off at depth about 2·log₂ n. Each level of partitioning does O(n) total work across all subarrays at that level, so the quicksort phase costs O(n log n). Every subarray still unsorted at the cutoff is handed to heap sort, which costs O(k log k) for a subarray of size k. Those subarrays don't overlap, so their total is O(n log n). Insertion sort runs only on subarrays of at most 16 elements, which adds O(n). The sum is O(n log n).
Exercise
In the code above, what happens to the fallback count if you replace the last-element pivot with a randomly chosen pivot and sort the already-sorted list again?
Show answer
The count is almost always 0. Random pivots split the array reasonably evenly with high probability, so the recursion depth stays well under 2·⌊log₂ n⌋ and heap sort is never called.