Sub topic 14
Choosing Between Merge Sort, Quicksort, and Heapsort
This chapter assumes you have read the earlier chapters on merge sort's running time, auxiliary space, and stability. It also assumes you have met quicksort and heapsort at least briefly: quicksort partitions around a pivot, and heapsort repeatedly extracts the maximum from a binary heap. You should be comfortable reading Big-O notation and short recursive Python functions.
All three algorithms are comparison sorts that run in O(n log n) time in the typical case, so asymptotic notation alone does not settle which one to use. The choice depends on worst-case guarantees, memory, stability, the data structure being sorted, and how the algorithm behaves on real hardware.
The Properties Side by Side
The table summarizes the standard textbook versions. "Extra space" means memory beyond the input itself.
| Property | Merge sort (array) | Quicksort (random pivot) | Heapsort |
|---|---|---|---|
| Best-case time | O(n log n), or O(n) with the "already ordered" skip | O(n log n) | O(n log n) |
| Average time | O(n log n) | O(n log n), about 1.39 n log₂ n comparisons | O(n log n), about 2 n log₂ n comparisons |
| Worst-case time | O(n log n) | O(n²) | O(n log n) |
| Extra space | O(n) buffer + O(log n) stack | O(log n) stack if you recurse on the smaller side | O(1) |
| Stable | Yes | No (in-place versions) | No |
| Memory access | Sequential scans | Sequential scans | Jumps between i and 2i+1 |
| Linked lists | Natural fit, O(1) extra space for nodes | Awkward | Impractical |
| Data larger than memory | Natural fit (external merge sort) | Poor | Poor |
| Parallelism | Easy: halves are independent, merges can be split | Easy after partitioning | Hard |
Each row affects real decisions, so the sections below go through them.
Worst-Case Guarantees
Merge sort's recurrence T(n) = 2T(n/2) + O(n) holds for every input, because the split point is always the middle. Quicksort's split point depends on the pivot. If the pivots keep landing near the minimum or maximum, the recurrence becomes T(n) = T(n − 1) + O(n), which is O(n²).
Random pivots make the quadratic case very unlikely, but they do not rule it out. Deterministic pivot rules such as "first element" or "median of three" can also be attacked: someone who knows the rule can build an input that triggers the worst case. That matters for any service that sorts data supplied by users.
Heapsort matches merge sort's O(n log n) worst case and needs only O(1) extra space. That pairing is the main reason it exists in practice.
Memory and Stability
Merge sort on arrays needs an O(n) buffer. For an array of 64-bit integers that is 8 bytes per element on top of the input. On a server with plenty of RAM, that cost rarely matters. In an embedded system, or when the array already fills most of memory, it can rule merge sort out.
Stability matters when you sort records by one key and the existing order carries meaning. Sorting a list of transactions by date after it was sorted by account number keeps each date's transactions grouped by account, but only if the sort is stable. Quicksort and heapsort can be made stable, for example by sorting (key, original_index) pairs, but that costs extra memory and comparisons and removes much of their advantage.
Hardware Effects: Why Quicksort Is Often Fastest
Counting comparisons hides the cost of memory access. Quicksort's partition loop walks two indices through contiguous memory and swaps in place. It touches each cache line a few times, and its working set shrinks as the recursion deepens until whole subarrays fit in cache.
Merge sort also scans sequentially, but it moves every element into a buffer and back on every level, so it writes about twice as much memory. Heapsort compares a parent at index i with children at 2i+1 and 2i+2. For large heaps those positions are far apart, so most sift-down steps miss the cache. As a result, heapsort is usually the slowest of the three on large in-memory arrays, even though its worst-case bound beats quicksort's.
Measuring the Difference
The script below counts comparisons for the three algorithms on random input and on input that is already sorted. The quicksort here deliberately uses the first element as its pivot, so you can see the quadratic case.
import random
class Counter:
def __init__(self):
self.n = 0
def merge_sort(a, c):
if len(a) <= 1:
return list(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_first_pivot(a, c):
a = list(a)
def qs(lo, hi):
if lo >= hi:
return
pivot = a[lo]
i = lo
for k in range(lo + 1, hi + 1):
c.n += 1
if a[k] < pivot:
i += 1
a[i], a[k] = a[k], a[i]
a[lo], a[i] = a[i], a[lo]
qs(lo, i - 1)
qs(i + 1, hi)
qs(0, len(a) - 1)
return a
def heapsort(a, c):
a = list(a)
n = len(a)
def sift(root, end):
while 2 * root + 1 < end:
child = 2 * root + 1
if child + 1 < end:
c.n += 1
if a[child] < a[child + 1]:
child += 1
c.n += 1
if a[root] < a[child]:
a[root], a[child] = a[child], a[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[0], a[end] = a[end], a[0]
sift(0, end)
return a
n = 400 # small enough that the quadratic quicksort stays under Python's recursion limit
inputs = {
"random": random.sample(range(n), n),
"sorted": list(range(n)),
}
for label, data in inputs.items():
for name, fn in [("merge", merge_sort),
("quick(first pivot)", quicksort_first_pivot),
("heap", heapsort)]:
c = Counter()
result = fn(data, c)
assert result == sorted(data)
print(f"{label:>6} {name:<20} {c.n:>7} comparisons")On random input you should see merge sort lowest (around 3,000), quicksort somewhat higher (around 4,000 to 5,000), and heapsort highest (around 6,000). On sorted input, merge sort drops to about 1,800 because each merge exhausts the left half early. Heapsort stays roughly the same. Quicksort jumps to exactly n(n − 1)/2 = 79,800. Its recursion depth also reaches 400, which is why the script keeps n small. At n = 2,000 this version would crash with RecursionError.
What Production Libraries Actually Do
Real libraries rarely ship any of the three in textbook form. They combine them so that each one covers another's weakness.
| Library call | Algorithm | Why |
|---|---|---|
| Python `sorted`, `list.sort` | Timsort (merge sort with run detection and an insertion-sort cutoff) | Stable, fast on partly ordered data, few comparisons |
| Java `Arrays.sort(Object[])` | Timsort | Stability is required for objects |
| Java `Arrays.sort(int[])` | Dual-pivot quicksort | Speed. Stability is irrelevant for primitives |
| C++ `std::sort` | Introsort: quicksort that switches to heapsort when recursion gets too deep, plus insertion sort for small ranges | Quicksort speed with an O(n log n) worst case |
| C++ `std::stable_sort` | Merge sort, with an O(n log² n) fallback if no buffer can be allocated | Stability |
| Rust `sort` / `sort_unstable` | Stable merge-based hybrid / pattern-defeating quicksort hybrid | Both options, chosen by the caller |
Introsort is a good example of design by combination. It runs quicksort, tracks recursion depth, and switches to heapsort once the depth passes about 2 log₂ n. Quicksort supplies the speed, heapsort caps the worst case, and insertion sort handles small subarrays where overhead dominates.
A Decision Procedure
In practice, the first rule outranks the flowchart: use your language's built-in sort unless you have measured a problem with it. Writing your own sort makes sense when you need something the library cannot give you. Examples include counting inversions during the merge, sorting a custom linked structure, sorting data on disk, or meeting a hard real-time bound on memory.
Common Errors When Choosing
- Treating "quicksort is fastest" as a rule. It holds on average for in-memory arrays of cheap keys. It fails for expensive comparisons, linked lists, disk-resident data, and adversarial input.
- Choosing heapsort for speed. Heapsort is chosen for its guarantees, not its speed. Its cache behavior usually makes it slower than both alternatives on large arrays.
- Forgetting the stack. A naive quicksort can recurse to depth n. Recursing on the smaller partition and looping on the larger one keeps the stack at O(log n).
- Ignoring existing order. Real data is often partly sorted. Timsort and merge sort with the "skip if already ordered" check exploit this, while heapsort cannot.
- Counting only the buffer. Merge sort's O(n) buffer is sometimes the deciding cost, but for small element types on modern machines it is often acceptable. Measure before rejecting it.
Exercise
You are writing firmware that must sort an array of 50,000 sensor readings (32-bit integers) within a fixed deadline. Only 4 KB of free RAM remains after the array is loaded, and equal readings are interchangeable. Which algorithm do you choose, and why are the other two worse here?
Show answer
Heapsort. It guarantees O(n log n) time, which you need to meet the deadline, and it uses O(1) extra space. Array merge sort needs a buffer of about 200 KB (50,000 × 4 bytes), which does not fit in 4 KB. Quicksort fits in memory with O(log n) stack, but its O(n²) worst case could miss the deadline. Stability does not matter because equal integers are indistinguishable, so heapsort loses nothing by being unstable.
Exercise
A web service sorts a user-uploaded list of records by "last name", and the list was previously sorted by "first name" so that ties should stay in first-name order. A colleague suggests a textbook quicksort with a median-of-three pivot because it benchmarked fastest. Give two separate reasons this is a poor choice.
Show answer
First, quicksort is not stable, so records with the same last name may lose their first-name order, which breaks the requirement. Second, the input is user-controlled, and a deterministic pivot rule like median-of-three can be defeated by a crafted input that forces O(n²) time, opening a denial-of-service risk. A stable O(n log n) sort such as merge sort or Timsort (the language's built-in stable sort) solves both problems.
Exercise
Why does introsort switch to heapsort rather than to merge sort when quicksort's recursion gets too deep?
Show answer
Introsort is designed as an in-place, unstable sort that uses only O(log n) extra space. Heapsort keeps those properties while capping the worst case at O(n log n). Switching to merge sort would require an O(n) buffer, which defeats the in-place goal. Merge sort's stability would also be wasted, because the quicksort phase has already reordered equal elements.