Heapsort and Priority Queues

A heap keeps one rule: every parent is at least as big as its children. That rule gives you the maximum in one step, an insert in about log2 n steps, and a sort that never needs extra memory.

Learn the binary heap of CLRS Chapter 6. Meet the array that is a tree, the sink that repairs it, the linear-time build, heapsort and the priority queue.

Pick an input order and press Play. The array first becomes a heap. Then the largest value leaves the root again and again, and the sorted run grows from the right. Then we build it piece by piece: the shape, the sink, the build, the sort and the queue.

You need a little Python and what a binary tree is. We build the rest from zero.

Re-taught from Chapter 6, Heapsort, of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (CLRS). The explanations, toys and counts here are our own, and a script checked every count.

Sort twelve numbers with a heap

Twelve fixed numbers. The counts are exact for each order: shuffled 50 comparisons and 35 swaps, sorted 55 and 40, reversed 47 and 28. The worst-case scale, 2 n log2 n, is 86 for n = 12.

Chapter 0

Pick the Next Job, Fast

Price three ways to hold a queue of jobs, and see why a sorted list and an unsorted list both fail

A print server holds 10,000 jobs, each with a priority number. Each time the printer frees up, the server must find the job with the highest priority and remove it. New jobs arrive all the time. Which way of storing the jobs keeps both actions fast?

Try the two obvious ways. A sorted array keeps the largest job at the end, so finding it is one step. But a new job must slide into its place, and up to n jobs move to make room. An unsorted array takes a new job at the end in one step. But finding the largest job means reading all n jobs.

A binary heap keeps less order than a sorted array and more than a pile. The largest job is always at the front. An insert or a removal touches one path from the top to the bottom, about log2 n jobs long.

Price one insert and one removal

Each bar is the worst-case steps for one new job plus one removal of the top job. Drag the queue size and watch which bars run away.

10,000

Worst-case steps. An array shift or scan reads up to n slots. A heap insert makes at most ⌊log2 n⌋ swaps, a removal at most 2⌊log2 n⌋ comparisons. Log scale.

OperationSorted arrayUnsorted arrayBinary heap
Insert a jobup to n moves1 stepabout log2 n
Look at the top job1 stepn reads1 step
Remove the top job1 stepn readsabout 2 log2 n

With numbers: 10,000 jobs and 1,000 removals per second. The unsorted array reads all 10,000 jobs per removal, so 10 million reads each second. The heap makes at most 13 swaps per insert and 26 comparisons per removal: 39 steps, or 39,000 each second. That is about 250 times less work.

The failure. The symptom is a queue that slows down as it fills. To measure it, time one removal at n jobs and at 10n jobs. If the time grows ten times, the structure is linear. The fix is the heap this lesson builds.

The road

  1. An array that is a tree: the index rules, the heap property, the height.
  2. MAX-HEAPIFY: sink one value that is too small.
  3. BUILD-MAX-HEAP: turn any array into a heap in linear time.
  4. Heapsort: the hero's sort phase, counted swap by swap.
  5. Priority queues: insert, remove the top, raise a key.
  6. Min-heaps and d-ary heaps: flip the rule, widen the tree.
  7. Top-K, medians and merging: three tricks built on a small heap.
  8. Heapsort in practice: why quicksort usually wins the race.
  9. The field guide: terms, numbers, code and links.
Why does an unsorted array make a slow priority queue?

Chapter 1

An Array That Is a Tree

Store a complete binary tree level by level, walk it with arithmetic, and state the one rule a max-heap keeps

Can a plain list be a tree without pointers? Yes, if the tree has no gaps. A complete binary tree fills each level from left to right before it starts the next. Write it out level by level: the root in slot 1, its children in slots 2 and 3, theirs in slots 4 to 7. CLRS counts from 1, so slot 0 stays empty.

Call a slot's number i, the slot above it parent(i), and the two below it left(i) and right(i).

Say it aloud

Parent of i equals the floor of i over 2. Left of i equals 2 i. Right of i equals 2 i plus 1.

i
i the index of a slot, a whole number from 1 to n.
parent(i)
parent of i the index of the slot directly above slot i.
⌊i/2⌋
the floor of i over 2 halve i and round down to a whole number.
left(i)
left of i the index of the left child of slot i.
right(i)
right of i the index of the right child, one slot after the left child.
In plain words

To go down, double i; add 1 for the right child. To go up, halve i and drop the remainder.

With numbers

In 90, 70, 80, 30, 60, 50, 40, 10, 20, 55 (n = 10), slot i = 5 holds 60. Its parent is ⌊5/2⌋ = 2 (70). Its left child is 10 (55). Slot 11 is past n, so 60 has one child.

Walk the tree with arithmetic

The tree and the array are the same data. Tap a node or slide the index.

5
10

A fixed max-heap. 0-based lists use 2i + 1, 2i + 2 and ⌊(i − 1)/2⌋.

Call the array A, so A[i] is the value in slot i, and call the number of values n. A max-heap has no child bigger than its parent.

Say it aloud

A of parent of i is at least A of i, for every i from 2 to n.

A[parent(i)]
A of parent of i the value stored in the parent's slot.
≥
is at least bigger than or equal to.
A[i]
A of i the value stored in slot i.
i = 2, …, n
for every i from 2 to n every slot except the root, which has no parent.
In plain words

Visit every slot i except the root and compare A[i] with its parent's value. One bigger child means A is not a max-heap.

With numbers

Slot 4 holds 30 under 70: 70 ≥ 30. Slot 10 holds 55 under 60: 60 ≥ 55. Every pair passes, so the maximum, 90, sits in slot 1.

The rule says nothing about siblings: 70 sits left of 80. Call the height h: the number of edges from the root down to the deepest leaf.

Say it aloud

h equals the floor of log base 2 of n.

h
h the height: edges from the root to the deepest leaf.
log2 n
log base 2 of n how many times you halve n to reach 1.
⌊ ⌋
the floor of round down to a whole number.
n
n the number of values in the heap.
In plain words

Each level holds twice the slots of the one above. Count how often you can halve n and keep 1 or more: that is h.

With numbers

For n = 10, log2 10 = 3.32, so h = 3: levels of 1, 2, 4 and 3 slots. For n = 1,000,000, log2 n = 19.93, so h = 19.

Slots ⌊n/2⌋ + 1 to n have no children. These leaves are ⌈n/2⌉ slots, about half the heap.

pythondef is_max_heap(A, n):              # A[1..n], A[0] unused
    return all(A[i // 2] >= A[i] for i in range(2, n + 1))

A = [None, 90, 70, 80, 30, 60, 50, 40, 10, 20, 55]
print(is_max_heap(A, 10))                # True

The failure. Code that mixes the 1-based rules with a 0-based list rejects valid heaps. Test on the heap above, and keep one convention per file.

In the max-heap 90, 70, 80, 30, 60, 50, 40 (slots 1 to 7), which value is the parent of the 60 in slot 5?

Chapter 2

MAX-HEAPIFY: Sink One Value

Repair a heap whose top is too small by swapping it down with its bigger child until it fits

The root holds 2, and its children hold 16 and 14. Below them, both subtrees are valid heaps. Only the top is wrong. How do you fix it without rebuilding everything?

MAX-HEAPIFY(A, i) sinks the value at slot i. It assumes both subtrees of slot i are already heaps.

  1. Find the largest of A[i] and its children that exist.
  2. If A[i] is the largest, stop. The rule holds at slot i.
  3. Otherwise swap A[i] with the bigger child.
  4. Move to that child's slot and go back to step 1.

Why the bigger child? If you swap with the smaller one, the bigger child ends up below a smaller parent, and the rule breaks at once.

Sink the small value

Purple rings mark the compared values; the warm node sinks. A red edge is a child bigger than its parent. Press Step and watch it move down and vanish.

Exact counts. The third array stops early.

With numbers, on 2, 16, 14, 12, 8, 7, 10, 4, 6, 3. Compare 2 with 16 and 14, and swap with 16. At slot 2, compare 2 with 12 and 8, and swap with 12. At slot 4, compare 2 with 4 and 6, and swap with 6. Slot 9 has no children, so stop. That is 3 swaps and 6 comparisons, and the array is 16, 12, 14, 6, 8, 7, 10, 4, 2, 3.

How far can a value sink? Call the height of slot i h(i): the number of levels below slot i. Call the swaps that MAX-HEAPIFY makes from slot i swaps(i).

Say it aloud

Swaps of i is at most h of i, which equals the floor of log base 2 of n over i.

swaps(i)
swaps of i how many swaps MAX-HEAPIFY makes when it starts at slot i.
h(i)
h of i the height of slot i: levels below it, 0 for a leaf.
⌊log2(n / i)⌋
the floor of log base 2 of n over i how many times you can double i and stay at or below n.
In plain words

Each swap moves the value one level down, and one level down doubles its index. So count how many times you can double i before it passes n. MAX-HEAPIFY can never swap more often than that.

With numbers

For n = 10 and i = 1: 10/1 = 10, log2 10 = 3.32, so h(1) = 3, and the 2 above sank 3 times. For i = 3: 10/3 = 3.33, log2 = 1.74, so h(3) = 1. Slot 3 has children 6 and 7 and no grandchildren.

Each level costs at most 2 comparisons, so a sink from the root costs at most 2⌊log2 n⌋.

pythondef max_heapify(A, i, size):            # A[1..size]; both subtrees of i are heaps
    while True:
        l, r, largest = 2 * i, 2 * i + 1, i
        if l <= size and A[l] > A[largest]: largest = l
        if r <= size and A[r] > A[largest]: largest = r
        if largest == i:
            return                          # A[i] wins: the rule holds here
        A[i], A[largest] = A[largest], A[i]
        i = largest                         # follow the value down

The failure. The symptom is a heap that still fails is_max_heap after the call. Two causes are common. The subtrees were not heaps to begin with, or the code compared against len(A) instead of the heap size. Measure with is_max_heap after every call in a test. The fix is the bottom-up order of Chapter 3 and an explicit size.

You call MAX-HEAPIFY on a node at depth 2 of a heap of height 5. What is the most swaps it can make?

Chapter 3

BUILD-MAX-HEAP in Linear Time

Sink every inner node from the bottom up, and count why the total work stays below n swaps

Start from 4, 1, 3, 2, 16, 9, 10, 14, 8, 7. MAX-HEAPIFY needs both subtrees to be heaps, and a leaf is a heap of one. So sink every other slot, from ⌊n/2⌋ back to 1. That loop is BUILD-MAX-HEAP: each slot it reaches has only heaps below it.

Build a heap from the bottom up

The warm slot sinks now. Press Play and watch the red edges vanish from the bottom up.

Exact counts: 7 swaps, 11 (the most for 15 values) and 0.

With numbers: slot 5 makes no swap, slot 4 swaps 2 with 14, and slot 3 swaps 3 with 10. Slot 2 swaps 1 with 16, then with 7. Slot 1 swaps 4 with 16, 14 and 8. That is 7 swaps and 14 comparisons, giving 16, 14, 10, 8, 7, 9, 3, 2, 4, 1.

The quick bound, n/2 calls of up to log2 n swaps, is loose: most slots sit near the bottom. So add the true limits from Chapter 2, the heights h(i).

Say it aloud

Total swaps is at most the sum over i from 1 to n of h of i, which is less than n.

total swaps
total swaps every swap BUILD-MAX-HEAP makes, over all its calls.
Σi=1n
the sum over i from 1 to n add one term for every slot.
h(i)
h of i the height of slot i, the most swaps a sink from there can make.
n
n the number of values.
In plain words

Group the slots by height: about n/4 have height 1, n/8 height 2, and so on. Add n/4 × 1 + n/8 × 2 + n/16 × 3 + …: the sum never reaches n.

With numbers

For n = 10 the heights are 3, 2, 1, 1, 1 and five zeros: 8. The CLRS array used 7. For n = 1,000,000 the sum is 999,993; the quick bound says 9.5 million.

Divide the grouped sum by n and it adds to 1:

1/4 + 2/8 + 3/16 + 4/32 + … = (1/2) × (1/2 + 2/4 + 3/8 + …) = (1/2) × 2 = 1

The inner sum of h/2h is 2: differentiate 1 + x + x2 + … = 1/(1 − x), multiply by x, set x = 1/2. The exact sum of heights is n minus the count of 1 bits in n.

Weigh the work by height

Each bar is slots at that height times the height. Drag n and compare the total with n.

1,000

Exact counts of slots per height.

On random arrays our runs made about 0.74 n swaps. Inserting values one by one (Chapter 5) is worse. On ascending input each value climbs to the top: 17,951,445 swaps for a million values, against 999,988 bottom-up.

The failure. Run the loop top-down and the CLRS array ends as 4, 16, 10, 14, 7, 9, 3, 2, 8, 1. The root is not the maximum. Catch it with is_max_heap and fix the order.

Why does BUILD-MAX-HEAP visit the slots from ⌊n/2⌋ down to 1, not from 1 up?

Chapter 4

Heapsort

Move the maximum to the end, shrink the heap, sink the new root, and repeat until the heap is empty

After the build, the largest value sits in slot 1. Its final place in a sorted array is slot n. So swap them. Slot n is now done, and the heap is one slot shorter. The new root is a small value from the bottom, so sink it.

  1. BUILD-MAX-HEAP on A[1..n].
  2. Swap A[1] with A[end], the last slot of the heap. A[end] is now in its final place.
  3. Shrink the heap: its size becomes end − 1.
  4. MAX-HEAPIFY(A, 1) over the shorter heap. Repeat from step 2 until end = 2.

Count each round of the sort

Each press runs one round: the root swap, then the sink. The bars below collect the sink swaps of each round. Blue slots are final.

Starts from the heap built in Chapter 3: 16, 14, 10, 8, 7, 9, 3, 2, 4, 1. Exact counts.

With numbers. Round 1 swaps 16 with 1, and the 1 sinks 3 levels: 14, 8, 10, 4, 7, 9, 3, 2, 1, then 16. Round 2 swaps 14 with 1, and the 1 sinks 2 levels. The nine rounds sink 3, 2, 2, 2, 2, 1, 1, 1 and 0 times: 14 sink swaps plus 9 root swaps. With the 7 build swaps, the whole sort makes 30 swaps and 42 comparisons.

How many swaps can heapsort make at most? The build makes fewer than n. Each of the n − 1 rounds makes one root swap and at most ⌊log2 n⌋ sink swaps.

Say it aloud

Swaps is at most n, plus n minus 1 times the quantity 1 plus the floor of log base 2 of n.

swaps
swaps every swap heapsort makes, build and sort together.
n
n the build's limit from Chapter 3, and the number of values.
(n − 1)
n minus 1 the number of rounds: one per value except the last.
1
1 the root swap that moves the maximum out in each round.
⌊log2 n⌋
the floor of log base 2 of n the height, the most sink swaps in a round.
In plain words

Pay n for the build. Then pay for n − 1 rounds. Each round costs one swap to move the maximum out, plus at most one swap per level for the sink.

With numbers

For n = 10: 10 + 9 × (1 + 3) = 46. The CLRS example used 30. For n = 1,000,000: 1,000,000 + 999,999 × 20, about 21 million, which grows like n log2 n.

Comparisons follow the same path, about 2 per level. On 100,000 random values we counted 1.82 n log2 n comparisons. The order of the input barely matters, so heapsort's worst case is O(n log n). It also sorts in place: it needs only a few extra variables, no second array.

Heapsort is not stable: equal keys can swap their order. Sort the pairs (2, a) and (2, b) by number, and heapsort returns (2, b) then (2, a).

pythondef heapsort(A):                       # A[1..n], A[0] unused
    n = len(A) - 1
    for i in range(n // 2, 0, -1):       # BUILD-MAX-HEAP
        max_heapify(A, i, n)
    for end in range(n, 1, -1):
        A[1], A[end] = A[end], A[1]       # the max goes to its final slot
        max_heapify(A, 1, end - 1)       # sink over the shorter heap

The failure. Call max_heapify(A, 1, end) without the shrink, and the maximum you just placed rises back to the root. The symptom is an output whose tail is not sorted. Measure with A[1:] == sorted(A[1:]) on random tests. The fix is the size end − 1.

After the first round of heapsort on a 10-value max-heap, where is the largest value?

Chapter 5

Priority Queues

Run the print server on a heap: take the top job, add a job, and raise a job's priority

Back to the print server. It needs a priority queue: a set of items that always hands out the item with the largest key, the item's priority number. A max-heap does this with four operations.

OperationWhat it doesCostHow
MAXIMUMLook at the top item1 stepRead A[1]
EXTRACT-MAXRemove the top itemO(log n)Move the last item to slot 1, shrink, sink it
INSERTAdd an itemO(log n)Put it in a new last slot, let it rise
INCREASE-KEYRaise one item's keyO(log n)Set the new key, let it rise

The new move is the rise, also called bubble-up. A value that grew may now beat its parent. So swap it with its parent while it is bigger, and stop at the root or when the parent wins. A rise climbs at most ⌊log2 n⌋ levels.

Run the print queue

Type a priority and press Insert to watch it rise. Press Take top to watch the last job sink from the root. Tap a node, then Raise it by 25.

Starts from the heap 90, 70, 80, 30, 60, 50, 40. Keys stop at 99 and the queue holds at most 15 jobs so the tree fits on a phone.

With numbers, INSERT 85 into 90, 70, 80, 30, 60, 50, 40. The 85 lands in slot 8. Its parent, slot 4, holds 30: swap. Its new parent, slot 2, holds 70: swap. Its parent, slot 1, holds 90: stop. Two swaps give 90, 85, 80, 70, 60, 50, 40, 30.

Now EXTRACT-MAX. Save 90 to return. Move the last value, 30, into slot 1 and shrink the heap to 7. Sink the 30: it swaps with 85, then with 70. Two swaps and 4 comparisons give 85, 70, 80, 30, 60, 50, 40.

In Python you rarely write this by hand. The heapq module keeps a min-heap in a plain list (Chapter 6). Store each job as a tuple of minus the priority, a counter and the job, so the largest priority comes out first.

pythonimport heapq, itertools
queue, tick = [], itertools.count()

def add(job, priority):
    heapq.heappush(queue, (-priority, next(tick), job))   # minus: largest first

def take_top():
    neg, _, job = heapq.heappop(queue)
    return job, -neg

add("report", 30); add("poster", 50); add("payroll", 90)
print(take_top())     # ('payroll', 90)

The failure. Push (priority, job) when two jobs share a priority and Python has no way to compare the job objects. The symptom is a TypeError that appears only on ties. Measure by pushing two equal priorities in a test. The fix is the counter in the middle of the tuple, which also makes ties come out in arrival order.

You INSERT the key 100 into a max-heap whose root is 80. How many swaps does it make?

Chapter 6

Min-Heaps and d-ary Heaps

Flip the rule to keep the smallest on top, and give each node more children to make the tree shorter

A min-heap keeps the opposite rule: every parent is at most its children, so the smallest value sits on top. The code is the same with each comparison flipped. Python's heapq is a min-heap on a 0-based list. heapq.heapify turns 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 into a heap in place: 1, 2, 3, 4, 7, 9, 10, 14, 8, 16. To get a max-heap from it, store minus each value.

A d-ary heap gives every node d children instead of 2. Number the slots from 0. Call the children of slot i child number k, for k from 0 to d − 1.

Say it aloud

Child k of i equals d times i plus k plus 1. Parent of i equals the floor of i minus 1 over d.

childk(i)
child k of i the index of slot i's child number k.
d
d the number of children per node: 2 for a binary heap.
i
i the index of a slot, counted from 0.
k
k which child, from 0 to d minus 1.
parent(i)
parent of i subtract 1, divide by d, round down.
In plain words

The root and the children of the i nodes before slot i fill the first d·i + 1 slots. So slot i's children start right after them, and child k is k slots further on. To go up, undo it.

With numbers

For d = 4 and i = 2, the children are 9, 10, 11 and 12. The parent of 11 is ⌊10/4⌋ = 2. For d = 2 and i = 2, the children are 5 and 6, which is the 0-based binary rule 2i + 1 and 2i + 2.

Widen the tree

More children make the tree shorter, so an insert climbs fewer levels. But a sink must compare all d children at every level. Drag d and watch the two costs part.

2
10⁶

Worst-case counts. Levels is the height of a d-ary heap of n slots. An insert compares once per level. A removal compares d times per level: d − 1 among the children and 1 with the parent.

With numbers, n = 1,000,000. A binary heap has 19 levels below the root, so an insert compares up to 19 times and a removal up to 38. A 4-ary heap has 10 levels: 10 for an insert, 40 for a removal. Inserts get about twice as cheap while removals cost about the same. That suits workloads with many more inserts or key changes than removals.

HeapInsertRemove topUse it when
Binary heapO(log n)O(log n)You want a simple, fast default
d-ary heapO(logd n)O(d logd n)Inserts and key changes far outnumber removals
Fibonacci heapO(1) amortizedO(log n) amortizedYou need cheap decrease-key in a proof, as in Dijkstra's O(E + V log V)
Pairing heapO(1)O(log n) amortizedYou want cheap merges and decrease-key in real code

The failure. Use heapq for "largest first" without negating. The symptom is a queue that hands out the smallest key. Measure by printing heap[0] after a few pushes. The fix is to push minus the key.

In Python you must take out the smallest item again and again from a changing collection. What do you use?

Chapter 7

Top-K, Medians and Merging

Keep the K largest of a stream with a small min-heap, track a running median with two heaps, and merge sorted lists

A stream of a billion numbers goes past, and you must keep the 100 largest. You cannot store the stream. Keep a min-heap of size K. Its root is the smallest of the K kept values: the gatekeeper. A new value gets in only if it beats the gatekeeper, and then it replaces it.

Guard the top K

Each new number meets the gatekeeper at the root. Teal numbers got in; grey ones lost. Watch the gatekeeper rise as the stream goes on.

3

The stream starts with the worked example 10, 4, 20, 5, 100, 3, 7, 50, then continues with fixed pseudo-random numbers from 1 to 999.

With numbers, K = 3 and the stream 10, 4, 20, 5, 100, 3, 7, 50. The first three fill the heap, with gatekeeper 4. Then 5 beats 4, and 100 beats 5, so the gatekeeper becomes 10. The 3 and the 7 lose, and the 50 beats 10. The heap ends as 20, 100, 50.

Each value costs at most log2 K swaps. The stream costs O(n log K) time and K slots of memory.

Running median. Keep two heaps. A max-heap lo holds the smaller half and a min-heap hi holds the larger half. Keep every value in lo at most every value in hi, and the sizes within 1. The median is the top of lo, or the average of both tops. For the stream 5, 15, 1, 3, the medians are 5, 10, 5 and 4. Each insert costs O(log n), but both heaps together store all n values.

Merge K sorted lists. Put the first item of each list in a min-heap of size K. Pop the smallest, output it, and push the next item from its list. Take K = 1,000 lists and N = 10,000,000 items. The merge costs about N log2 K = 108 steps. Sorting everything again costs N log2 N = 2.3 × 108.

Problem saysPatternHeap
K largest, K most frequentTop-KMin-heap of size K
K smallest, K closestTop-K, flippedMax-heap of size K
Running medianTwo heapsMax-heap and min-heap
Merge sorted listsK-way mergeMin-heap of list heads
Combine the two rarest symbolsHuffman codingMin-heap of counts

Huffman coding uses the same pop-two, push-one loop. Take symbol counts 5, 9, 12, 13, 16 and 45 per 100 characters. Huffman's codes need 224 bits, against 300 for a fixed 3-bit code.

The failure. Keep the top K in a max-heap. The symptom is slow code, because each new value meets the smallest kept value, which a max-heap hides. Measure the time per item as K grows. The fix is the min-heap, whose root is that smallest value.

You track the running median of 1,000,000 numbers with two heaps. How much memory does it use?

Chapter 8

Heapsort in Practice

Race heapsort against quicksort and merge sort, and see why the jumps between slots cost more than the comparisons

Heapsort has the best guarantees on paper: O(n log n) in the worst case and no extra memory. Yet most libraries do not use it as their main sort. Why?

PropertyHeapsortQuicksortMerge sort
Worst caseO(n log n)O(n2)O(n log n)
Average caseO(n log n)O(n log n)O(n log n)
Extra memoryO(1)O(log n) stackO(n)
StableNoNoYes
Reads memory in orderNo: jumps from i to 2iYes: scansYes: two scans

Memory arrives in cache lines of 64 bytes, about 8 numbers. A read next to the last read is almost free. A read far away can cost a hundred times more. Quicksort's partition walks the array slot by slot. Heapsort jumps from slot i to slot 2i, so deep in a big heap almost every step lands in a new cache line.

Race three sorts

Each sort runs here on the same random array. Left: comparisons, as a multiple of n log2 n. Right: the share of reads within 8 slots of the read before. Press New data, or change n.

Live counts in your browser. Quicksort uses a random pivot and a left-to-right partition. Merge sort reads two runs at once, so a single "previous read" does not describe it; its nearby-read bar is left out. Nearby reads stand in for cache hits; real timings depend on the machine.

With numbers, from our runs at n = 100,000: heapsort made 1.82 n log2 n comparisons, quicksort 1.20 and merge sort 0.92. Only 37% of heapsort's reads landed within 8 slots of the read before, against 99% for quicksort. Heapsort loses on both counts.

So libraries combine them. Introsort (Musser, 1997) runs quicksort and watches the depth of its recursion. If the depth passes about 2 log2 n, the input is bad for quicksort, so it switches to heapsort for that part. You get quicksort's speed on most inputs and heapsort's worst-case guarantee on all of them. Python's own sort is a stable merge sort instead, so it spends O(n) memory to keep equal keys in order.

The failure. A team picks heapsort for its guarantee and finds it slower than the library sort on large arrays. The symptom is a big gap in wall time with similar comparison counts. Measure with a cache profiler, or count far reads as this device does. The fix is the library sort, with heapsort kept as the fallback inside it.

Why does introsort switch from quicksort to heapsort when the recursion gets deep?

Chapter 9

The Field Guide

Keep the terms, the counts, the checks and the code in one place

A binary heap is a complete binary tree stored level by level in an array, with every parent at least as big as its children. A sink repairs a too-small value and a rise repairs a too-big one, each in O(log n). The bottom-up build takes fewer than n swaps. Heapsort then moves the maximum to the end n − 1 times. A priority queue is the same heap with insert and remove-the-top.

Terms

TermMeaning
Complete binary treeEvery level full except the last, which fills from the left
Max-heap propertyA[parent(i)] ≥ A[i] for every slot but the root
Height hEdges from the root to the deepest leaf: ⌊log2 n⌋
MAX-HEAPIFY (sink)Swap a too-small value down with its bigger child until it fits
Rise (bubble-up)Swap a too-big value up with its parent until it fits
BUILD-MAX-HEAPSink slots ⌊n/2⌋ down to 1; fewer than n swaps
Priority queueItems with keys; always hands out the largest (or smallest) key
Stable sortEqual keys keep their input order; heapsort is not stable

The numbers from this page

WhatNumberWhy it matters
Height for n = 1,000,00019Every heap step touches at most 20 levels
Build swaps, CLRS array of 107 (limit 8)The sum of heights caps the build
Build swaps, random arraysabout 0.74 nLinear in practice too
Insert-one-by-one, 106 ascending17,951,445 swapsAgainst 999,988 for the bottom-up build
Heapsort on the CLRS array30 swaps, 42 comparisonsUnder the limit of 46 swaps
Comparisons at n = 100,0001.82, 1.20, 0.92 × n log2 nHeapsort, quicksort, merge sort
Nearby reads at n = 100,00037% against 99%Heapsort against quicksort: the cache gap

Before you trust heap code

The core, 0-based

pythondef sink(a, i, size):                     # max-heap, a[0..size-1]
    while True:
        l, r, big = 2 * i + 1, 2 * i + 2, i
        if l < size and a[l] > a[big]: big = l
        if r < size and a[r] > a[big]: big = r
        if big == i: return
        a[i], a[big] = a[big], a[i]
        i = big

def rise(a, i):
    while i > 0 and a[(i - 1) // 2] < a[i]:
        p = (i - 1) // 2
        a[i], a[p] = a[p], a[i]
        i = p

def heapsort(a):
    n = len(a)
    for i in range(n // 2 - 1, -1, -1): sink(a, i, n)    # build: fewer than n swaps
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]                      # max to its final slot
        sink(a, 0, end)                                   # the heap is now a[0..end-1]

def push(a, x): a.append(x); rise(a, len(a) - 1)
def pop_max(a):
    a[0], a[-1] = a[-1], a[0]; top = a.pop(); sink(a, 0, len(a)); return top

Keep going

The takeaway. Keep only the order you need. "Every parent beats its children" costs O(log n) to maintain and gives you the top in one step. Build it bottom-up and it costs less than n.
Which statement about a binary max-heap of n values is true?

Now press Present or Teach. Explain from memory the index rules, the sink, the build's limit of n swaps, and one round of heapsort. Then go back to the hero, play the reversed input, and say why its build makes no swaps at all.

Credit and source

This lesson re-teaches Chapter 6, Heapsort, of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms. Introsort is from David Musser, "Introspective Sorting and Selection Algorithms" (1997). The toys and counts here are our own.

CLRS Chapter 6: Heapsort and Priority Queues
The book · Back to Gleams