Sort a million exam scores from 0 to 100. Merge sort can need 18,951,425 comparisons. Counting sort compares nothing and takes 2,000,100 steps. Widen the range to a billion, and counting sort needs a billion steps.
Pick the range of the keys and watch the three costs move. Then we prove why no comparison sort can beat about n log2 n, and build three sorts that read the keys instead.
You need Python loops and lists and a first sort such as merge sort. We build the rest from zero.
Based on Chapter 8, "Sorting in Linear Time", of Introduction to Algorithms (CLRS) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). The explanations, toys and devices are our own.
Model counts for n = 1,000,000. Merge sort: its worst-case comparisons only. Counting sort: 2n + k steps. Radix sort: base 256, d passes of 2n + 255 steps. Chapters 2 to 4 derive each formula.
Chapter 0
Count the scores instead of comparing them
You have a million exam scores. Each one is a whole number from 0 to 100. Merge sort would compare pairs of scores, about 19 million times. But a million scores can take only 101 different values.
So keep 101 counters, one for each score. Walk the list once and add 1 to the counter of each score. Then walk the counters from 0 to 100 and write each score out as many times as its counter says. No two scores are ever compared.
Each dot is one score. It drops into the column for its value, 0 on the left and 100 on the right. Pick how many scores, then press Tally.
Illustrative scores, seeded. Merge sort's number is its exact worst case for that many items.
A comparison sort is a sort that learns the order only by testing two keys at a time: is ai ≤ aj? Merge sort, heapsort, quicksort and insertion sort are all comparison sorts. Chapter 1 proves that every one of them needs about n log2 n comparisons on its worst input.
The tally above is not a comparison sort. It uses the value of a key as an address. That is the whole trick of this chapter, and it has a price: the sort must know something about the keys, such as their range.
Failure. The scores arrive as decimals, such as 87.5, and the tally puts 87.5 in column 87. Symptom: the output is out of order inside a column. Measure: check that each output value is no larger than the next one. Fix: tally only whole-number keys, or scale them first (87.5 becomes 175 out of 200).
Chapter 1
Draw a sort as a tree of yes or no questions and count its leaves
Sort three keys a1, a2, a3 by comparing them. Each test has two answers. So a sort that compares is a decision tree: each inner node is one test, each branch is one answer and each leaf is one final order.
Pick one of the six inputs. The path lights test by test: left means yes, right means no. The leaf names the sorted order by position.
This tree is the one insertion sort follows on three keys (CLRS Figure 8.1). Any other correct sort has its own tree, with at least six leaves.
The tree must have a leaf for every possible order. Three keys have 3! = 6 orders, so it needs 6 leaves. The worst-case number of tests is the height of the tree: the longest path from the root to a leaf. A tree of height h has at most 2h leaves, because each level can at most double them.
So 2h must reach the number of orders, n! (say "n factorial", the product 1 × 2 × ... × n). Take the log of both sides.
H is at least log base two of n factorial.
Count the orders, n factorial. Find how many doublings reach that count, and round up. No comparison sort can finish every input with fewer tests than h.
For n = 4, n! = 24 and log2 24 = 4.58, so h is at least 5. For n = 10, log2(3,628,800) = 21.79, so at least 22 tests.
How fast does log2(n!) grow? Stirling's formula approximates n! for large n and gives this.
Log base two of n factorial is about n log base two of n, minus one point four four n.
Multiply n by log2 n, then take off 1.44 for each key. The floor grows like n log2 n, which CLRS writes Ω(n lg n) in Theorem 8.1.
For n = 1,000,000: n log2 n = 19,931,569 and 1.44 n = 1,442,695, which leaves 18,488,874. The exact floor is 18,488,885. Merge sort's worst case is 18,951,425, only 2.5% above it.
| n | Floor ⌈log2(n!)⌉ | Merge sort, worst | Insertion sort, worst |
|---|---|---|---|
| 3 | 3 | 3 | 3 |
| 4 | 5 | 5 | 6 |
| 10 | 22 | 25 | 45 |
| 1,000 | 8,530 | 8,977 | 499,500 |
Failure. A benchmark shows a new comparison sort beating the floor. Symptom: fewer comparisons than log2(n!) on the test set. Measure: run it on all 24 orders of 4 keys and take the maximum; it must be at least 5. Fix: the tests held only easy inputs, so report the worst case.
Chapter 2
Turn counts into addresses, then place each key from the right
The tally of Chapter 0 writes plain numbers. Real records carry data along with the key, such as a name with a score. Counting sort moves whole records and keeps equal keys in their input order. It sorts n keys, each a whole number from 0 to k, in three passes.
Why do running totals give addresses? If 7 keys are ≤ 3, then the last 3 belongs in slot 6 of B, counting from 0. Each later 3 takes the slot to its left.
C of v becomes C of v plus C of v minus one.
Go from v = 1 up to k. Add the counter on the left into each C[v]. Each counter then holds the count of keys up to and including v.
A = [2, 5, 3, 0, 2, 3, 0, 3], k = 5. The counts are C = [2, 0, 2, 3, 0, 1]. The running totals are [2, 2, 4, 7, 7, 8]: for v = 3, C[3] = 3 + 4 = 7.
Top row: the input A. Middle row: the counters C, one per value 0 to 5. Bottom row: the output B. Press Step for one operation, or Run.
The CLRS worked example (Figure 8.2), with indexes from 0 as in Python.
Count the steps: n additions to count, k additions for the totals, n placements. That is the cost.
T equals two n plus k.
Two steps for each key, plus one for each possible value. If k is no bigger than about n, the sort is linear in n.
The example: 2 × 8 + 5 = 21 steps. A million scores from 0 to 100: 2,000,100. But 10,000 keys from 0 to 10,000,000 cost 10,020,000 steps, almost all on empty counters.
Failure. The keys are 64-bit IDs. Symptom: the program runs out of memory before it sorts anything. Measure: the count array needs k + 1 slots, 1.8 × 1019 here. Fix: if k is much bigger than n, use radix sort.
Chapter 3
Sort on the last digit first, and let stability carry the order
Counting sort chokes when k is huge. Split each key into digits instead. A 3-digit number has a ones, a tens and a hundreds digit, and each digit is only 0 to 9. Radix sort runs a stable counting sort on one digit at a time, starting with the least significant digit.
That order looks backwards. It works because each pass is stable. After the pass on the ones digit, ties on the tens digit keep the ones order. After the tens pass, ties on the hundreds digit keep the tens-and-ones order. After the last pass, the whole key is in order.
The purple digit is the one this pass sorts on. Press Next pass three times. Then switch the walk off, reset, and run the same three passes.
The CLRS example (Figure 8.3). With the toggle off, each pass walks left to right, which reverses ties.
Each pass is a counting sort whose largest key is the largest digit. Call the number of digits d and the largest digit k (9 in base 10).
T equals d times, open bracket, two n plus k, close bracket.
Run one counting sort per digit. Each costs 2n + k steps. Multiply by d.
The seven numbers: d = 3, k = 9, so T = 3 × (14 + 9) = 69 steps. A million 32-bit keys in base 256: d = 4, k = 255, so T = 4 × 2,000,255 = 8,001,020.
Failure. A pass uses an unstable sort. Symptom: the output is almost sorted, with some ties in the wrong order. Measure: in the device, the reversed walk ends with 355 before 329. Fix: make each pass stable; for counting sort, walk from the right.
Chapter 4
Trade fewer passes against bigger count arrays
A computer stores a key as b bits, such as 32. Radix sort can cut those bits into digits of any width. Call the width r bits. A digit then takes 2r values, and a key has ⌈b/r⌉ digits.
Wide digits mean few passes, but each pass walks a count array of 2r slots. Narrow digits mean small arrays but many passes. The best width sits between.
T of r equals the ceiling of b over r, times, open bracket, two n plus two to the r minus one, close bracket.
Cut the b bits into r-bit digits and count the passes. Each pass costs 2n plus one step per counter. Multiply. Try several r and keep the smallest T.
n = 1,000,000 and b = 32. For r = 8: 4 × (2,000,000 + 255) = 8,001,020. For r = 16: 2 × (2,000,000 + 65,535) = 4,131,070, the best. For r = 24: 2 × (2,000,000 + 16,777,215) = 37,554,430.
The curve is T(r) on a log scale. The dot is your width; the green ring is the best one. Drag r, then change n.
32-bit keys. The step count follows the formula above; real speed also depends on caches.
CLRS (Lemma 8.4) picks r near log2 n. Then 2r is about n, and the cost is about b n / log2 n. Then round r so that it divides b with few bits left over. For a million keys, log2 n is 19.9. But r = 20 still needs 2 passes, and r = 16 does those 2 passes with a smaller array.
Failure. A sort with r = 16 on 1,000 keys runs slower than with r = 8. Symptom: time grows as n shrinks. Measure: 2 × 67,535 = 135,070 steps, against 4 × 2,255 = 9,020. Fix: pick r from n, not once for all inputs.
Chapter 5
Spread real numbers into n buckets and tidy each one
Your keys are real numbers between 0 and 1, such as 0.78. They have no digits to count. If they are spread evenly, use bucket sort. Split the range into n equal buckets and drop each key into its bucket. Sort each bucket with insertion sort, then join the buckets in order.
Ten keys: [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]. Bucket 2 gets 0.26, 0.21 and 0.23, and insertion sort orders them. Buckets 0, 4, 5 and 8 stay empty.
Each bar is one bucket and its height is how many keys it holds. Switch between even and skewed keys, and change n.
Seeded toy keys. Skewed keys are u4 for even u, so most fall near 0.
Why linear? Call the number of keys in bucket i ni. Insertion sort on it costs about ni2 steps, so the question is the average of ni2.
The expected value of n-i squared equals two minus one over n.
Each key lands in bucket i with chance 1/n, so a bucket holds 1 key on average. The square of its size averages just under 2. Add n buckets: under 2n steps in all.
For n = 10: E = 2 − 0.1 = 1.9 per bucket, 19 for all ten. For n = 1,000,000: 1.999999 per bucket, about 2 million in all, which is linear (CLRS Section 8.4).
Failure. The keys are not even. Symptom: one bucket holds a large share of the keys. Measure: track the fullest bucket; with 200 skewed keys it holds 56, against 6 when even. Fix: choose bucket edges from a sample, or fall back to a comparison sort.
Chapter 6
Keep ties in their input order, so that sorts can stack
A class list is in name order. You sort it by score. Ana, Dee and Gus all scored 85. A stable sort keeps equal keys in their input order, so Ana, Dee and Gus stay in name order. An unstable sort may shuffle them.
The list starts in name order. The three 85s are in orange, and "in #" gives each row's input place. Pick a sort and press Sort.
The heapsort order is what our heapsort code produces on this list. Another heapsort may break ties in another way.
Stability is what lets two sorts stack. Sort by name, then sort by score with a stable sort: each score group is in name order. This is radix sort's trick, one digit at a time.
| Stable | Not stable |
|---|---|
| Counting sort (walk from the right) | Heapsort |
| Radix sort (with stable passes) | Quicksort (usual partition) |
| Merge sort (take left on ties) | Selection sort (swap version) |
| Insertion sort, Timsort | C++ std::sort (introsort) |
Any sort becomes stable if you sort pairs (key, input index) instead of keys. Equal keys then differ by index, and the earlier one wins. It costs one extra number per record.
Failure. A report sorts orders by date, then by customer, with an unstable sort. Symptom: each customer's orders come out in random date order. Measure: inside each customer, check that dates never go down. Fix: use a stable sort for the second pass, or sort once on the pair (customer, date).
Chapter 7
Race six sorts on the same data and find where each one wins
Now put everything on one track. Three comparison sorts (merge sort, quicksort, heapsort) race three linear sorts (counting, radix and bucket) on the same keys. You choose the kind of keys and how many.
The bars use a log scale: each grid line is 10 times the one before. Choose the keys and the size; the sorts run on real data in your browser.
Seeded toy data. Comparison sorts: comparisons counted while they run. Counting: 2n + k. Radix: base 256, d(2n + 255). Bucket: 2n plus its insertion comparisons. Quicksort picks a random pivot.
| Try | Winner | Why |
|---|---|---|
| Integers 0 to n, n = 1,000 | Bucket, then counting | Small range: 3,000 counting steps against 8,715 merge sort comparisons |
| Integers 0 to n³, n = 1,000 | Bucket, then merge | k = 109: counting needs a billion steps |
| Even reals, any n | Bucket | About one key per bucket |
| Skewed reals, n = 10,000 | Merge | The first bucket holds about 1,000 keys, so bucket sort takes 297,669 steps |
Look at the cube case. At n = 1,000 the keys go up to 109, so radix sort needs 4 passes. That is 9,020 steps, a little more than merge sort's 8,714 comparisons. At n = 10,000 the keys need 40 bits, which is 5 passes, and radix sort edges ahead: 101,275 against 120,483.
Failure. A team picks bucket sort because it won a benchmark on even data. Symptom: the real data has most keys near 0, and the sort does 12 times more work (24,525 steps become 297,669 in the arena). Measure: log the size of the fullest bucket on real inputs. Fix: test the sort on the data you will sort.
Chapter 8
Read the keys first, then pick the algorithm
Each linear sort buys its speed with one assumption. Counting sort needs a small range. Radix sort needs keys with a fixed number of digits. Bucket sort needs an even spread. If none holds, a comparison sort is the safe choice.
Pick the kind of keys you have. The lit path shows the questions that lead to the pick. Toggle stability for the fallback.
Costs are the step models of Chapters 2 to 5 for n = 1,000,000; the comparison sort shows its floor, log2(n!).
| Sort | Steps | Extra space | Stable | Needs |
|---|---|---|---|---|
| Merge sort | Θ(n log n) | n | Yes | Only a way to compare |
| Heapsort | Θ(n log n) | O(1) | No | Only a way to compare |
| Quicksort | Θ(n log n) average, n2 worst | log n | No | Only a way to compare |
| Counting sort | 2n + k | n + k | Yes | Integer keys 0 to k, k about n or less |
| Radix sort | d(2n + k) | n + k | Yes | Keys with d digits |
| Bucket sort | about 2n average, n2 worst | n | Yes, with insertion sort | An even spread over a known range |
Library sorts mix these ideas. Python's sorted() is Timsort: insertion sort on short runs, then stable merges. C++ std::sort is introsort: quicksort that switches to heapsort if it goes too deep. GPU libraries sort with radix sort, because each pass splits cleanly across many threads.
Radix sort also sorts strings of equal length. Ten-letter codes in base 256 take 10 passes. With a million codes that is 10 × 2,000,255 = 20,002,550 steps, near merge sort's 18,951,425 comparisons. But each of merge sort's comparisons may read up to 10 letters.
Failure. A service sorts user IDs with radix sort and then adds negative IDs. Symptom: negative IDs land after the positive ones. Measure: check the order across zero. Fix: flip the sign bit of each key before sorting, and flip it back after.
Chapter 9
Keep the numbers, the checks and the code in one place
A sort that only compares is a decision tree with n! leaves. So its worst case is at least log2(n!), about n log2 n. Counting, radix and bucket sort read the keys instead. They run in linear time when their assumption holds: a small range, few digits, or an even spread.
| Term | Meaning | Number to remember |
|---|---|---|
| Decision tree | A comparison sort drawn as yes or no tests | 3 keys: 6 leaves, height 3 |
| Lower bound | Fewest worst-case comparisons | ⌈log2(n!)⌉: 5 for 4 keys, 22 for 10 |
| Counting sort | Count, running totals, place from the right | 2n + k: 21 steps on the 8-key example |
| Running totals | C[v] = keys ≤ v | [2, 0, 2, 3, 0, 1] becomes [2, 2, 4, 7, 7, 8] |
| Radix sort | Stable passes, last digit first | d(2n + k): 69 steps for 7 three-digit numbers |
| Digit width | Bits per radix pass | r = 16 for a million 32-bit keys: 4,131,070 steps |
| Bucket sort | n buckets, insertion sort each, join | E[ni2] = 2 − 1/n |
| Stable | Equal keys keep their input order | Needed by every radix pass |
pythondef counting_sort(A, k, key=lambda x: x): C = [0] * (k + 1) for x in A: # 1. count C[key(x)] += 1 for v in range(1, k + 1): # 2. running totals C[v] += C[v - 1] B = [None] * len(A) for x in reversed(A): # 3. place, right to left: stable C[key(x)] -= 1 B[C[key(x)]] = x return B def radix_sort(A, bits=32, r=8): # non-negative ints below 2**bits mask = (1 << r) - 1 for shift in range(0, bits, r): # least significant digit first A = counting_sort(A, mask, lambda x: (x >> shift) & mask) return A def bucket_sort(A): # reals in [0, 1) n = len(A) buckets = [[] for _ in range(n)] for x in A: buckets[min(int(n * x), n - 1)].append(x) return [x for b in buckets for x in sorted(b)]
Now press Present or Teach and explain three things from memory. Why does a comparison sort need log2(n!) tests? How do running totals turn into addresses? Why does radix sort start with the last digit? Then go back to the million keys, pick 0 to 1 billion, and say why radix sort wins.
This lesson re-teaches Chapter 8, "Sorting in Linear Time", of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, published by MIT Press. Theorem 8.1 is the lower bound; Lemmas 8.3 and 8.4 are the radix sort costs. The toys, step models and devices are our own; we checked every count on this page by running the code.