Merge Sort, Quicksort & Heapsort
Three ways to sort in O(n log n) by comparing elements.
Three algorithms sort items with about comparisons, and each one wins somewhere. Merge sort is stable and never has a bad day, quicksort is usually the fastest in practice, and heapsort needs no extra memory and has no bad inputs at all. No comparison sort can do asymptotically better, so what separates them is everything else: memory, stability, cache behavior and the worst case.
What you’ll learn
- Analyze insertion sort through inversions: time, so on sorted input and in the worst and average cases.
- Implement merge sort, solve its recurrence exactly, and count inversions as a by-product.
- Implement quicksort with a Lomuto partition, prove its expected comparisons, and explain its worst case and Hoare's alternative.
- Build a heap in time and sort with it in worst-case time and extra space.
- Use library sorts correctly: keys and comparators, stable versus unstable sorts, and strict weak orderings.
The baseline: insertion sort and inversions
Every fast sort is measured against the obvious one. Insertion sort keeps a sorted prefix and inserts the next element into it by shifting larger elements one slot right. Its loop invariant: before iteration , the prefix holds the first input elements in sorted order.
The right measure of its work is the number of inversions : the pairs with . A sorted array has none, a reversed one all .
def insertion_sort(a):
for j in range(1, len(a)):
key, i = a[j], j - 1
while i >= 0 and a[i] > key: # invariant: a[0..j-1] is sorted
a[i + 1] = a[i] # each shift removes exactly one inversion
i -= 1
a[i + 1] = keySorts in place and is stable: the strict > never moves a key past an equal one.
Shifts. A shift moves the key past one larger element to its left, so it removes exactly one inversion, and nothing else changes the order. The loop ends with the array sorted, so the number of shifts is exactly the number of inversions:
Comparisons. Every comparison either causes a shift or ends the inner loop, and each of the inner loops ends at most once by a failed comparison:
Worst and average cases. Reversed input has all pairs inverted. In a uniformly random permutation each pair is inverted with probability , so by linearity of expectation:
So insertion sort takes time: on sorted input, in the worst and average cases, and when every element starts at most places from its final position, because then two elements can be inverted only if they start fewer than places apart, so each element is inverted with fewer than elements to its right. It is an adaptive sort.
How many shifts does insertion sort make on ?
Show the answer
8
Count the inversions. 3 precedes three smaller keys (1, 1, 2); 4 precedes 1 and 2; 5 precedes 2; 9 precedes 2 and 6. That is . The two 1s are equal, so they form no inversion, and the strict comparison never shifts one past the other.
Merge sort: a recurrence you can solve exactly
Merge sort is divide and conquer in its purest form: split the array into halves, sort each recursively, and merge the two sorted runs by repeatedly taking the smaller front element. Taking from the left run on ties keeps it a stable sort. The merge also sees, for free, how many elements of the left run each right element jumps over, which is exactly the number of inversions between the halves:
def sort_count(a):
"""Return (sorted copy of a, number of inversions in a)."""
n = len(a)
if n <= 1:
return a[:], 0
left, x = sort_count(a[:n // 2])
right, y = sort_count(a[n // 2:])
out, inv, i, j = [], x + y, 0, 0
while i < len(left) and j < len(right):
if right[j] < left[i]: # strict: on ties the left run goes first (stable)
out.append(right[j]); j += 1
inv += len(left) - i # right[j] jumps over everything left in `left`
else:
out.append(left[i]); i += 1
out += left[i:] + right[j:]
return out, invsort_count([3, 1, 2]) returns ([1, 2, 3], 2). Tested against a brute-force inversion count on thousands of random arrays. The inversion count measures how far one ranking is from another (the Kendall tau distance).
Recurrence. Each comparison of a merge outputs one element, and the last element needs no comparison, so merging elements costs at most comparisons. With the worst-case count:
Powers of two. For , divide by and unroll; each level adds :
So when is a power of 2, and by induction for every (checked against the recurrence for all up to 5000):
Cost. That is 49 comparisons for and 8,977 for . Every level of the recursion also copies all elements through a buffer, so merge sort takes time on every input, with extra space. Inversions split into those inside the left half, inside the right half, and across, and the merge counts the third kind exactly, so counting adds only per output element:
Think first Merge sort's comparison count on 16 keys is at most 49. In the widget it makes 32 comparisons on sorted and on reversed input. Why exactly 32 in both cases?
When every key of one run is smaller than every key of the other, the merge compares each key of the smaller-keyed run once, then copies the other run without comparing: comparisons for two runs of length . On sorted input the left run always runs out first, on reversed input the right run does. Each of the 4 levels merges pairs of equal runs whose sizes add up to 16, so it makes 8 comparisons, and . Merge sort is not adaptive in time, though: it still copies every element at every level.
Quicksort: partition, then recurse
Quicksort (Hoare, 1961) does its work before recursing. A partition step picks a pivot and rearranges so that the keys pivot come first, then the pivot, then the larger keys. The pivot now sits at its final index , and the two sides are sorted independently. Nothing needs merging, and everything happens in place.
The partition below is Lomuto's, the version in CLRS and in the widget. Its invariant: pivot , while is not yet examined.
import random
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
while lo < hi:
p = partition(a, lo, hi)
if p - lo < hi - p: # recurse on the smaller side, loop on the larger,
quicksort(a, lo, p - 1) # so the call stack stays O(log n) deep
lo = p + 1
else:
quicksort(a, p + 1, hi)
hi = p - 1
def partition(a, lo, hi): # Lomuto, with a uniformly random pivot
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
pivot, i = a[hi], lo
for j in range(lo, hi): # invariant: a[lo..i-1] <= pivot < a[i..j-1]
if a[j] <= pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i] # the pivot lands at its final index
return iTested on thousands of random arrays, many with repeated keys. Each recursive call gets at most half of the range, so the stack never exceeds frames, even when the pivots are bad; the time can still be quadratic.
Each pair is compared at most once. Name the keys by rank, . Every comparison is between the current pivot and another key of its range, and after its partition the pivot is never touched again. With when and are ever compared:
When they meet. Until some pivot is drawn from , all of these keys stay in one range. If that first pivot is or , the two are compared; if it lies strictly between them, they land on different sides and never meet. Each of the keys is equally likely to be drawn first:
Sum. Group the pairs by ; there are pairs for each :
Size. With , the leading term is . The approach to that constant is slow, because of the term: is about 1.10 at and 1.24 at .
Randomized quicksort sorts the keys . What is the probability that the keys 1 and 100 are ever compared with each other?
- 1, since the first pivot is compared with every key
Show the answer
C.
They are compared only if the first pivot drawn from , which here is the very first pivot of the whole sort, is 1 or 100: probability . Any other first pivot sends them to different sides for good. Neighbors in sorted order, such as 40 and 41, are always compared.
Heapsort, and the three side by side
Heapsort (Williams, 1964) keeps a max-heap inside the array itself: the children of index are and , and every parent is at least as large as its children (the heap property). Build the heap, then repeat: swap the root, which is the maximum, to the end of the heap region, shrink the region by one, and sift down the new root.
def heapsort(a):
n = len(a)
def sift_down(i, size): # restore the max-heap property below index i
while True:
big, l, r = i, 2 * i + 1, 2 * i + 2
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
for i in range(n // 2 - 1, -1, -1): # Floyd's bottom-up construction: O(n)
sift_down(i, n)
for end in range(n - 1, 0, -1): # move the maximum behind the shrinking heap
a[0], a[end] = a[end], a[0]
sift_down(0, end)In place and tested like the others. The same sift-down serves both phases; only the heap's size changes.
Building is linear. Floyd's construction (1964) sifts down the nodes from index back to 0, the bottom-up heapify. A node of height sinks at most levels, with 2 comparisons per level, and only about nodes have height :
Extracting is logarithmic. Each of the extractions sifts a root down a heap of height at most . (For the build alone: on 1,000 keys in increasing order, where every key sinks to the bottom, the code above makes 1,982 comparisons, under .)
In place, not stable, not cache-friendly. Heapsort needs extra memory on every input. Its swaps carry keys over long distances, past equal keys, so it is not stable, and its jumps from to touch memory far apart, which caches dislike. Heapsort is the guarantee, rarely the fastest choice.
| Algorithm | Comparisons, worst case | Comparisons, typical | Extra space | Stable | Notes |
|---|---|---|---|---|---|
| Insertion sort | random; sorted | yes | adaptive, ; best for tiny or nearly sorted ranges | ||
| Merge sort | between and the worst case | yes | sequential scans; the core of Timsort and of external sorting | ||
| Quicksort, random pivot | expected | stack | no | in place, sequential scans, usually fastest | |
| Heapsort | a little less | no | guaranteed and in place; scattered memory access |
Recognizing it
In practice you rarely write a sort; you decide to sort, and call the library. Sorting first is the right move when order turns a hard question into a local one:
- A greedy choice needs an order: intervals by end time, jobs by deadline or by length.
- Events happen at times: sort the starts and ends, then sweep once (sweep line).
- Pairs, gaps or nearest values: sort, then use two pointers or look at neighbors.
- Many queries on fixed data: sort once, then binary search each query.
- Constraints around to allow an preprocessing step, under the rule of thumb of simple steps per second.
| Problem, in brief | Key idea | Cost |
|---|---|---|
| Merge overlapping intervals | sort by start; extend the current interval while the next one starts before it ends | |
| The most meetings in progress at once | sort the start and end events, ends first on ties; sweep with a counter | |
| How far one ranking is from another | count inversions with merge sort | |
| Arrange numbers so that their concatenation is largest | sort with the comparator " before iff " | string comparisons |
| Order jobs to minimize the total waiting time | shortest job first, proved by an exchange argument |
from functools import cmp_to_key
people = [("Lee", "Ana", 31), ("Kim", "Ben", 25), ("Lee", "Cal", 25), ("Kim", "Dee", 40)]
print(sorted(people, key=lambda p: (-p[2], p[0]))) # oldest first, ties by last name
print(sorted(people, key=lambda p: p[0])) # stable: ties keep their order
def largest_concatenation(nums):
"""Arrange non-negative integers so that their concatenation is as large as possible."""
def order(x, y): # x goes first if xy > yx
return (x + y < y + x) - (x + y > y + x)
s = ''.join(sorted(map(str, nums), key=cmp_to_key(order)))
return '0' if s[0] == '0' else s
print(largest_concatenation([3, 30, 34, 5, 9])) # 9534330Python's sorted and list.sort are Timsort, guaranteed stable. A key tuple sorts by several keys at once, and negating a number reverses its order. Checked against brute force over all permutations.
#include <algorithm>
#include <cstdio>
#include <string>
#include <tuple>
#include <vector>
struct Person { std::string last, first; int age; };
int main() {
std::vector<Person> v = {{"Lee", "Ana", 31}, {"Kim", "Ben", 25}, {"Lee", "Cal", 25}, {"Kim", "Dee", 40}};
// Oldest first, ties by last name: compare tuples, a strict weak ordering.
std::sort(v.begin(), v.end(), [](const Person& a, const Person& b) {
return std::tie(b.age, a.last) < std::tie(a.age, b.last);
});
// Group by last name, keeping the age order inside each group.
std::stable_sort(v.begin(), v.end(), [](const Person& a, const Person& b) { return a.last < b.last; });
for (const auto& p : v) std::printf("%s %s %d\n", p.first.c_str(), p.last.c_str(), p.age);
// Prints: Dee Kim 40, Ben Kim 25, Ana Lee 31, Cal Lee 25 (one per line).
// Never: [](int x, int y) { return x <= y; }. Not a strict weak ordering: undefined behavior.
}C++17. std::sort is not stable and, since C++11, must make comparisons in the worst case (implementations typically use introsort). std::stable_sort takes with a spare buffer and without one.
Common bugs.
- A comparator that is not a strict weak ordering:
<=, comparisons with NaN, random or inconsistent answers. In C++ the behavior is undefined and can read out of bounds; Java's Timsort may throw "Comparison method violates its general contract!"; Python returns a meaningless order. - Comparing by subtraction:
return a - b;in Java or C overflows when and are large with opposite signs. UseInteger.compare(a, b)or compare with<. - Losing stability: sorting by a secondary key and then by the primary key with an unstable sort scrambles the secondary order.
- Recursion depth: a recursive quicksort with a fixed pivot rule recurses deep on sorted input, far past Python's default recursion limit of 1,000.
- Numbers as strings:
"10" < "9"is true. Anda.sort()returnsNone;sorted(a)returns a new list.
You get meetings as half-open time intervals and must report the largest number of meetings in progress at the same moment. Which approach fits?
- Compare every pair of meetings and count the overlapping pairs
- Sort the start and end events by time, ends before starts on ties, and sweep with a counter that adds 1 at a start and subtracts 1 at an end, tracking its maximum
- Sort the meetings by length and greedily pick the shortest ones
- Binary search over the start times
Show the answer
B. Sort the start and end events by time, ends before starts on ties, and sweep with a counter that adds 1 at a start and subtracts 1 at an end, tracking its maximum
The number of meetings in progress changes only at events, so one sweep over the sorted events sees every candidate moment: in all. Processing ends before starts on ties means a meeting ending at 10 and one starting at 10 do not overlap, as half-open intervals require.
Key takeaways
- Insertion sort costs with inversions: linear on nearly sorted input, quadratic on average, and every sort that only swaps neighbors is quadratic on average.
- Merge sort makes at most comparisons, is stable, needs extra space, and counts inversions as a by-product.
- Randomized quicksort makes expected comparisons on every input and works in place, but it is in the worst case and not stable.
- Heapsort builds a heap in and sorts in worst-case time with extra space, at the price of more comparisons and poor locality.
- Use the library sort: a stable sort or a key tuple for several keys, and a comparator that is a strict weak ordering.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Insertion sort runs on an array of keys in which every key is at most 3 positions away from its sorted position. What is its running time?
- , like any insertion sort
- , which is not linear
Show the answer
C.
Two keys can be inverted only if they start fewer than positions apart, so there are fewer than inversions, and insertion sort takes time. This is why hybrid sorts finish nearly sorted pieces with insertion sort.
An adversary picks the input to your quicksort, which chooses each pivot uniformly at random. Which statement is true?
- The expected number of comparisons is on every input; the expectation is over the pivots, not the input
- The worst-case running time is
- The adversary can choose an input that makes the expected time
- The expected time is only on random inputs
Show the answer
A. The expected number of comparisons is on every input; the expectation is over the pivots, not the input
The proof that pairs are compared with probability uses only the randomness of the pivots, so it holds for every input. Unlucky pivots can still cost , but with tiny probability; no input is bad in expectation.
Why does bottom-up heap construction take time, even though it calls sift-down about times and a sift-down can take steps?
- Most nodes are near the bottom: a node of height sifts down at most levels, and only about nodes have height , so the total is levels
- Sift-down takes time on average
- It actually takes time in the worst case
- The input is usually nearly sorted
Show the answer
A. Most nodes are near the bottom: a node of height sifts down at most levels, and only about nodes have height , so the total is levels
Half the nodes are leaves and do nothing, a quarter sift down at most one level, an eighth at most two, and so on. The weighted sum converges: at most levels and comparisons in all, whatever the input.
You must sort records in memory with almost no extra space and a guaranteed worst case; stability does not matter. Which algorithm fits?
- Merge sort
- Quicksort with random pivots
- Insertion sort
- Heapsort
Show the answer
D. Heapsort
Heapsort works in place with extra space and makes at most about comparisons on every input. Introsort, which runs quicksort and falls back to heapsort, offers the same guarantee and is faster in practice.
A C++ program calls std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; }) and crashes on some inputs with many equal values. Why?
std::sortis not stable- The comparator is not a strict weak ordering, since it says comes before , so the behavior is undefined and an unguarded scan can run past the end of the range
- Lambdas cannot be passed to
std::sort - Comparing ints with
<=overflows
Show the answer
B. The comparator is not a strict weak ordering, since it says comes before , so the behavior is undefined and an unguarded scan can run past the end of the range
std::sort requires comp(a, a) to be false, together with transitivity of the order and of equivalence. Implementations rely on this, for example by scanning for an element not less than the pivot without a bounds check. Use < instead.
Go deeper
- The Ω(n log n) Sorting Lower Bound · Decision trees, log₂ n!, and lower bounds for other problems by reduction.
- Quicksort in Depth · Expected 2n ln n comparisons, pivot rules, duplicate keys and introsort.
- Sorting in Practice: Timsort to Powersort · Runs, adaptive merging and the sorts inside Python, Java, Rust and Go.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 2, 6 and 7.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), chapter 2.
- C. A. R. Hoare, "Quicksort," The Computer Journal 5(1) (1962), 10–16.
- J. W. J. Williams, "Algorithm 232: Heapsort," Communications of the ACM 7(6) (1964).