Sub topic 10
Introsort: Quicksort with a Safety Net
This chapter assumes you know how quicksort partitions around a pivot, what heapsort and insertion sort do, and Big-O notation. It also builds on the earlier chapter on which classic algorithms are stable.
The problem introsort solves
Quicksort is fast in practice. It sorts in place, its inner loop is simple, and it uses the cache well. Its weakness is the worst case. If the pivot choices keep producing lopsided partitions, the running time grows to O(n²) and the recursion goes n levels deep. Median-of-three pivot selection makes this less likely, but crafted inputs can still trigger it.
David Musser introduced introsort ("introspective sort") in 1997. It runs quicksort while watching its own recursion depth. If the depth passes a limit, introsort stops partitioning that range and finishes it with heapsort. Heapsort is slower on average, but it always runs in O(n log n) and needs no extra memory.
The three phases
| Phase | When it runs | Why | Stable? |
|---|---|---|---|
| Quicksort | Default for ranges larger than a small threshold | Fast average case, in place | No |
| Heapsort | When recursion depth exceeds about 2·⌊log₂ n⌋ | Guarantees O(n log n) | No |
| Insertion sort | On ranges of about 16 elements or fewer | Low overhead on tiny inputs | Yes, but it cannot repair order already lost |
A working implementation
import random
THRESHOLD = 16
def introsort(a):
max_depth = 2 * max(0, len(a).bit_length() - 1) # 2 * floor(log2 n)
_introsort(a, 0, len(a), max_depth)
def _introsort(a, lo, hi, depth):
while hi - lo > THRESHOLD:
if depth == 0:
heapsort(a, lo, hi)
return
depth -= 1
p = partition(a, lo, hi)
# Recurse on the smaller side, loop on the larger: stack stays O(log n).
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 partition(a, lo, hi):
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] # median of three becomes the pivot
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 heapsort(a, lo, hi):
n = hi - lo
def sift(root, end):
while True:
child = 2 * root + 1
if child >= end:
return
if child + 1 < end and a[lo + child] < a[lo + child + 1]:
child += 1
if a[lo + root] < 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(start, n)
for end in range(n - 1, 0, -1):
a[lo], a[lo + end] = a[lo + end], a[lo]
sift(0, end)
def insertion_sort(a, lo, hi):
for i in range(lo + 1, hi):
current = a[i]
j = i - 1
while j >= lo and a[j] > current:
a[j + 1] = a[j]
j -= 1
a[j + 1] = current
data = [random.randrange(5) for _ in range(10_000)]
expected = sorted(data)
introsort(data)
print(data == expected) # TrueThe test input has only five distinct values. That is the worst case for this Lomuto partition, because every element equal to the pivot lands on one side. Plain quicksort would recurse thousands of levels deep and run in quadratic time. Introsort reaches its depth limit of 26 and hands the range to heapsort.
Why introsort is not stable
Each phase moves elements in its own way. Quicksort's partition swaps elements across long distances, so equal keys can pass each other. Heapsort does the same when it moves elements through the heap. Insertion sort is stable, but it only runs on small ranges that are already scrambled. Introsort therefore makes no stability promise. This is why C++ std::sort, which libstdc++ implements as introsort, is unstable, and why .NET's Array.Sort, also an introsort, is documented as unstable.
Exercise
For an array of 1,000,000 elements, what depth limit does this implementation use, and what happens to a range that is still more than 16 elements long when the limit is reached?
Show answer
floor(log2 1,000,000) is 19, so the limit is 2 × 19 = 38. A range that still has more than 16 elements at that depth is sorted entirely by heapsort, so the total running time stays O(n log n).
Exercise
You sort records by priority with std::sort and records with equal priority come out in a different order from the input. Is this a bug in std::sort? Name two fixes.
Show answer
It is not a bug. std::sort is an introsort, which does not guarantee stability. One fix is to call std::stable_sort. The other is to add each record's original index as a tiebreaker in the comparator.