Sub topic 12
Heap Sort vs. Quicksort and Merge Sort
This chapter assumes you have already worked through the heap sort implementation, its complexity analysis, and the discussion of stability from earlier chapters. You should also be comfortable with Big-O notation and with the basic idea of quicksort (partition around a pivot, then recurse) and merge sort (split in half, sort each half, merge). You do not need to have implemented either of those two before.
Heap sort, quicksort, and merge sort are the three standard comparison sorts that run in O(n log n) time. On paper they look similar. In practice they behave quite differently, and each one is the right choice in different situations. This chapter compares them on guarantees, memory, stability, and real-world speed, and ends with a way to decide between them.
The Guarantees Side by Side
Start with what each algorithm promises. The table below uses n for the number of elements and assumes a typical textbook implementation of each: quicksort with in-place partitioning and merge sort on an array.
| Property | Heap sort | Quicksort | Merge sort |
|---|---|---|---|
| Worst-case time | O(n log n) | O(n²) | O(n log n) |
| Average time | O(n log n) | O(n log n) | O(n log n) |
| Best-case time | O(n log n) for distinct keys | O(n log n) | O(n log n), or O(n) with a "skip merge if already ordered" check |
| Extra space | O(1) | O(log n) stack if you recurse on the smaller side first, O(n) if you don't | O(n) buffer |
| Stable | No | No (in-place versions) | Yes |
| Typical comparisons | about 2n log₂ n | about 1.39n log₂ n on average | between ½n log₂ n and n log₂ n |
| Memory access pattern | Jumps between i and 2i+1 | Sequential scans | Sequential scans |
| Works well on linked lists | No | Awkward | Yes |
Heap sort is the only one of the three that gives both a worst-case O(n log n) bound and O(1) extra space. Quicksort gives up the worst-case bound. Merge sort gives up the memory. That combination is heap sort's main selling point. Its weaknesses are stability and the constant factors hidden inside the O(n log n).
Measuring Instead of Guessing
Big-O hides constants, so it helps to count work directly. The script below counts key comparisons for all three algorithms on three kinds of input: random, already sorted, and all equal. The quicksort is a plain textbook version that always uses the last element as its pivot, with no randomization. It uses an explicit stack instead of recursion so the bad cases don't hit Python's recursion limit.
import random
class Counter:
def __init__(self):
self.n = 0
def heap_sort(a, c):
def sift_down(start, end):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end:
c.n += 1
if a[child + 1] > a[child]:
child += 1
c.n += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(start, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(0, end)
return a
def merge_sort(a, c):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid], c)
right = merge_sort(a[mid:], c)
out = []
i = j = 0
while i < len(left) and j < len(right):
c.n += 1
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
def quicksort(a, c):
# Lomuto partition with the last element as pivot (naive on purpose).
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi:
continue
pivot = a[hi]
i = lo
for j in range(lo, hi):
c.n += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
stack.append((lo, i - 1))
stack.append((i + 1, hi))
return a
def run(name, data):
for label, fn in [("heap", heap_sort), ("quick", quicksort), ("merge", merge_sort)]:
c = Counter()
result = fn(list(data), c)
assert result == sorted(data)
print(f"{name:8} {label:6} {c.n:>12,}")
random.seed(1)
n = 2000
run("random", [random.randint(0, 10**6) for _ in range(n)])
run("sorted", list(range(n)))
run("equal", [7] * n)When you run it, you should see a pattern like this:
- Random input: quicksort and merge sort each use roughly 20,000 to 25,000 comparisons. Heap sort uses noticeably more, around 38,000. That matches the constant factors in the table.
- Sorted input: the naive quicksort jumps to about 2,000,000 comparisons, which is n(n−1)/2. Each partition peels off one element. Heap sort stays near its random-input count. Merge sort drops to about half its usual count, because every merge exhausts the left half first.
- All-equal input: the naive quicksort is quadratic again, because nothing is strictly less than the pivot. Heap sort becomes nearly linear, since every sift-down stops after one or two comparisons.
The lesson is that heap sort's cost hardly depends on the input. That makes it predictable. It also means heap sort never gets the shortcuts that partially ordered data gives the other two.
Why Heap Sort Loses on Real Hardware
Even when comparisons are cheap, heap sort is usually slower than a well-tuned quicksort, often by a factor of 2 or more on large arrays of integers. Comparison counts explain part of this. The rest comes from how the hardware behaves.
Cache locality
Quicksort's partition step and merge sort's merge step both read memory sequentially. The CPU prefetches the next cache line before it is needed, so most reads are fast. Heap sort's sift-down jumps from index i to index 2i+1. Near the root those indices sit close together. Deeper in the tree they are far apart, so each level of a sift-down on a large array can be a cache miss. This penalty grows as the array outgrows the CPU caches.
Wasted work in the sort-down phase
Each extraction swaps the last leaf into the root. That leaf is usually one of the smallest values, so it almost always sinks back to the bottom. Every level costs two comparisons: one to pick the larger child and one to compare against it. Most of the second comparisons are predictable "keep going" results, but the processor still has to execute them. The bottom-up heap sort variant, covered in a later chapter, removes most of this waste.
Branch prediction
The "which child is larger" branch in sift-down is close to a coin flip on random data. Modern CPUs mispredict such branches often, and each misprediction stalls the pipeline. Quicksort has a similar unpredictable branch in partitioning, but each one does less work per element moved.
Failure Modes and Gotchas
Each algorithm has a characteristic way to go wrong. Knowing these failure modes matters more for choosing among them than the average-case speed does.
Quicksort: adversarial and degenerate inputs
A fixed pivot rule can be forced into O(n²). Sorted input breaks last-element pivots, as the script showed. Median-of-three pivots have known "killer" sequences of their own. If an attacker controls the input, for example data from an HTTP request that a server sorts, quadratic behavior becomes a denial-of-service risk. Random pivots make the bad case unlikely but do not rule it out. Three-way partitioning fixes the duplicate-key problem but not the adversarial one.
Merge sort: memory
The O(n) buffer is a real cost when sorting a large array in memory-constrained environments such as embedded systems or kernels. It also adds allocation and copying overhead. In-place merge sort variants exist, but they are complicated and slower.
Heap sort: instability and random access
Heap sort scrambles the relative order of equal keys, so you cannot use it to sort by a secondary key after a primary one. It also needs O(1) random access by index. On a linked list, getting to child 2i+1 costs O(n), which ruins the algorithm. Merge sort is the natural choice for linked lists.
Parallelism and external data
Merge sort and quicksort split into independent subproblems that can run on separate cores. Merge sort also extends naturally to external sorting, where data lives on disk and you merge sorted runs. The sort-down phase of heap sort works on one shared heap and is hard to parallelize.
Where Heaps Win Outright: Partial Sorting
One case favors heaps clearly. If you need only the k largest or smallest elements, you can keep a heap of size k while scanning the input. That costs O(n log k) time and O(k) space. Neither quicksort nor merge sort gives you that for free. Quickselect can find the k-th element in O(n) average time, but it rearranges the whole array and has the same worst case as quicksort. Priority queues, event schedulers, and streaming top-k queries all use heaps for this reason, even in systems where a full sort would use something else.
Choosing Between Them
The diagram below shows a decision process that matches how library authors and practitioners usually choose.
In short:
- Use merge sort when you need stability, when the data is in a linked list or on disk, or when you can parallelize. Python's
sortedand Java's object sort use Timsort, a merge sort hybrid, because stability is part of their contract. - Use quicksort when you want the fastest typical in-memory sort of primitive values and stability does not matter.
- Use heap sort when the worst case must be bounded and extra memory is not available, for example in real-time systems, kernels, and embedded code.
The last two options do not exclude each other. Combining them gives quicksort's typical speed with heap sort's worst-case bound, and the next chapter shows how introsort does it.
Exercise
A server sorts arrays of up to 10 million 64-bit integers taken from user requests. Memory per request is tightly limited, the order of equal values does not matter, and response time must never degrade badly. Rank plain fixed-pivot quicksort, merge sort, and heap sort for this job and justify the ranking.
Show answer
Heap sort ranks first. It guarantees O(n log n) even on adversarial input and needs only O(1) extra memory, and stability is not required. Merge sort is second. Its worst case is safe, but the O(n) buffer, about 80 MB for 10 million 64-bit values, breaks the memory limit. Plain fixed-pivot quicksort is last. Users control the input, so they can trigger its O(n²) worst case and slow the server down. An introsort would beat all three, since it keeps quicksort's speed and falls back to heap sort.
Exercise
In the comparison-counting script, heap sort needs far fewer comparisons on the all-equal array than on the random one, while the naive quicksort needs far more. Explain both effects in terms of the code.
Show answer
In heap sort, sift_down breaks as soon as a[root] >= a[child]. With all keys equal, that test succeeds right away, so each call does at most two comparisons and the whole sort is about O(n). In the Lomuto quicksort, the test a[j] < pivot is never true. So i stays at lo, the pivot lands at the left edge, and each partition removes only one element. The total is n(n−1)/2 comparisons, which is O(n²).
Exercise
You must sort a singly linked list of one million records by timestamp, keeping records with equal timestamps in their original order. Which of the three algorithms fits, and why do the other two fit poorly?
Show answer
Merge sort fits. It is stable, and on a linked list it can split and merge by relinking nodes with no extra buffer and no random access. Heap sort fails twice: it is not stable, and it depends on jumping to index 2i+1, which costs O(n) per jump on a list. In-place quicksort is not stable either, and partitioning a singly linked list is awkward and loses quicksort's cache advantage.