Sub topic 10
Introsort: Quicksort with a Safety Net
This chapter assumes you know how quicksort partitions an array, what a binary heap is, and why insertion sort is fast on small or nearly sorted inputs. The chapter on classic algorithms covered why quicksort and heapsort are unstable. Here you will see how introsort combines quicksort, heapsort and insertion sort into a single algorithm. That algorithm keeps quicksort's speed and avoids its worst case, and it ends up unstable.
The Problem Introsort Solves
Quicksort is fast on average. Its inner loop is short, it moves memory sequentially, and it sorts in place. Its weakness is the worst case. If the pivot keeps landing near the smallest or largest element, every partition peels off only a few elements. The recursion depth grows to O(n) and the running time to O(n²).
Better pivot selection makes bad cases rarer but does not remove them. Median-of-three picks the median of the first, middle and last elements, and it handles sorted and reverse-sorted input well. Inputs built to defeat it still exist. David Musser called them "median-of-3 killer" sequences in his 1997 paper that introduced introsort. In a library, a quadratic worst case is a real risk. An attacker who controls the input, such as a list of IDs in a web request, can make a server do O(n²) work.
Heapsort has a guaranteed O(n log n) worst case, but in practice it is slower than quicksort. It jumps around the array between parent and child indices, which hurts cache performance, and it does more comparisons per element.
Introsort, short for "introspective sort", runs quicksort while watching its own recursion depth. If the depth passes a limit, the current subarray is probably a bad case, and introsort hands that subarray to heapsort. Small subarrays go to insertion sort.
The Three Parts
| Part | Job | Why it is used there |
|---|---|---|
| Quicksort with median-of-three | Main work on large ranges | Fastest on typical inputs, in place |
| Heapsort | Fallback when recursion gets too deep | O(n log n) worst case, in place |
| Insertion sort | Finishes small ranges | Low overhead for roughly 16 elements or fewer |
The depth limit is usually 2 × ⌊log₂ n⌋. A well-balanced quicksort reaches depth about log₂ n, so the limit allows twice the ideal depth before giving up on quicksort for that range.
| n | ⌊log₂ n⌋ | Depth limit |
|---|---|---|
| 100 | 6 | 12 |
| 10,000 | 13 | 26 |
| 1,000,000 | 19 | 38 |
The fallback applies only to the subarray that hit the limit. Other parts of the array keep using quicksort.
A Complete Implementation
The Python version below follows the structure of the GNU C++ library's std::sort. It has a quicksort loop with a depth budget, a heapsort fallback, and a final insertion sort over the whole array. Python already has a better built-in sort, so this code is for reading and experiments.
import math
import random
THRESHOLD = 16
def introsort(a, key=lambda x: x):
"""Sort list a in place and return it."""
if len(a) < 2:
return a
depth_limit = 2 * int(math.log2(len(a)))
_introsort_loop(a, 0, len(a), depth_limit, key)
_insertion_sort(a, 0, len(a), key)
return a
def _introsort_loop(a, lo, hi, depth, key):
# Ranges of THRESHOLD or fewer elements are left for the final insertion sort.
while hi - lo > THRESHOLD:
if depth == 0:
_heapsort(a, lo, hi, key)
return
depth -= 1
cut = _partition(a, lo, hi, key)
# Recurse into the smaller side and loop on the larger one,
# so the call stack stays O(log n) deep.
if cut - lo < hi - cut:
_introsort_loop(a, lo, cut, depth, key)
lo = cut
else:
_introsort_loop(a, cut, hi, depth, key)
hi = cut
def _median_of_three(a, lo, hi, key):
mid = lo + (hi - lo) // 2
x, y, z = a[lo], a[mid], a[hi - 1]
kx, ky, kz = key(x), key(y), key(z)
if kx < ky:
if ky < kz:
return y
return z if kx < kz else x
if kx < kz:
return x
return z if ky < kz else y
def _partition(a, lo, hi, key):
"""Hoare partition. Returns cut with a[lo:cut] <= pivot <= a[cut:hi]."""
pk = key(_median_of_three(a, lo, hi, key))
i, j = lo - 1, hi
while True:
i += 1
while key(a[i]) < pk:
i += 1
j -= 1
while pk < key(a[j]):
j -= 1
if i >= j:
return j + 1
a[i], a[j] = a[j], a[i]
def _heapsort(a, lo, hi, key):
n = hi - lo
def sift_down(root, end):
while True:
child = 2 * root + 1
if child >= end:
return
if child + 1 < end and key(a[lo + child]) < key(a[lo + child + 1]):
child += 1
if key(a[lo + root]) < key(a[lo + child]):
a[lo + root], a[lo + child] = a[lo + child], a[lo + root]
root = child
else:
return
for start in range(n // 2 - 1, -1, -1):
sift_down(start, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
sift_down(0, end)
def _insertion_sort(a, lo, hi, key):
for i in range(lo + 1, hi):
current = a[i]
k = key(current)
j = i - 1
while j >= lo and key(a[j]) > k:
a[j + 1] = a[j]
j -= 1
a[j + 1] = current
if __name__ == "__main__":
data = [random.randrange(1000) for _ in range(10_000)]
assert introsort(data[:]) == sorted(data)
print("sorted correctly")Details Worth Noticing
The final insertion sort runs once over the whole array, not once per small range. When the quicksort loop stops, every element sits inside its own unsorted block of at most 16 elements, and every block holds only keys that belong between its neighbours. So no element moves more than about 16 positions, and one pass costs O(16 · n) = O(n). A single pass has lower overhead than many small calls.
The loop recurses into the smaller side and iterates on the larger one. That bounds the call stack at O(log n) frames even before the depth limit applies. The depth limit protects running time. The smaller-side rule protects stack space.
The partition uses strict < in both scans, so the scans stop on elements equal to the pivot. That sounds wasteful, but it splits runs of equal keys evenly between the two sides. A scan that skipped equal keys would put all of them on one side, and an array of identical values would then hit the quadratic case.
The median-of-three pivot also keeps the scans in bounds. At least one element on each side of the range compares as greater than or equal to the pivot, or less than or equal to it, so i and j always stop before leaving lo..hi. Production C++ code goes further and moves the median into a fixed position so it can use "unguarded" loops without index checks.
Why Introsort Is Not Stable
Introsort builds on two unstable algorithms. The Hoare partition swaps elements across long distances, and any element can jump past an equal one. Heapsort scrambles equal keys too. The final insertion sort is stable, but it only fixes local disorder, and by then equal keys are already out of order. You can test this directly:
import random
from introsort_demo import introsort # save the code above as introsort_demo.py
records = [(random.randrange(3), i) for i in range(1000)]
result = introsort(records[:], key=lambda r: r[0])
in_order = all(a[1] < b[1] for a, b in zip(result, result[1:]) if a[0] == b[0])
print(in_order) # almost always FalseComplexity and Guarantees
| Measure | Plain quicksort | Introsort |
|---|---|---|
| Average time | O(n log n) | O(n log n) |
| Worst-case time | O(n²) | O(n log n) |
| Extra space | O(log n) to O(n) stack | O(log n) stack |
| Stable | No | No |
The worst-case bound holds for a simple reason. Each element passes through at most 2 log₂ n partition levels, each costing O(n) in total across that level. Heapsort then finishes any leftover range in O(m log m). On normal inputs the heapsort fallback almost never runs, so introsort runs at plain quicksort speed.
Where Introsort Runs
C++11 changed std::sort from "N log N comparisons on average" to O(N log N) comparisons in the worst case. Plain quicksort cannot meet that requirement, and introsort is the usual way to meet it.
- GNU libstdc++
std::sortis introsort with a threshold of 16 and a final insertion sort, much like the code above. - Microsoft's STL
std::sortis also an introsort. - LLVM's libc++ added the heapsort fallback only in version 14. Before that, its
std::sortcould go quadratic on adversarial input. - .NET's
Array.Sorthas used introsort since .NET Framework 4.5.
The next chapter covers pattern-defeating quicksort. It keeps introsort's safety net and adds faster handling for sorted runs, many duplicates and other patterns.
Exercise
An array of 1,000,000 elements is sorted with introsort using a depth limit of 2 × ⌊log₂ n⌋. What is the limit, and what happens to a subarray whose partitioning reaches that depth while it still has 5,000 elements?
Show answer
⌊log₂ 1,000,000⌋ is 19, so the limit is 38. When a range still has more than 16 elements and its budget reaches 0, introsort stops partitioning that range and heapsorts its 5,000 elements in O(m log m) time. Other ranges keep using quicksort.
Exercise
In the partition, why do both scans stop on elements equal to the pivot (strict < comparisons) instead of skipping them?
Show answer
Stopping on equal keys swaps them across the cut, so a long run of equal keys is split roughly in half. If the scans skipped equal keys, an array of identical values would partition into one empty side and one side with everything, giving O(n) depth. Introsort would then fall back to heapsort for the entire array.
Exercise
The final insertion sort is stable. Why does introsort still not preserve the input order of equal keys?
Show answer
The quicksort partitions and any heapsort fallback have already swapped equal elements past each other over long distances before the insertion pass runs. Insertion sort keeps the order it receives and never restores the original order, so the scrambling stays.