Sorting in Linear Time

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.

Sort a million keys

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

A Million Scores, Few Values

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.

Tally the scores

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.

200

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).

  1. The wall: why comparing costs at least log2(n!) tests.
  2. Counting sort: the tally, made stable. The hero's blue bar.
  3. Radix sort: sort big keys one digit at a time. The purple bar.
  4. Digit size: how many bits each radix pass should read.
  5. Bucket sort: spread real numbers into buckets.
  6. Stability: why ties must keep their order.
  7. The arena: race six sorts on four kinds of data.
  8. Choose a sort: from the data to the algorithm.
  9. Field guide: numbers, code and the credit.
A million scores take only the values 0 to 100. How many counters does the tally need?

Chapter 1

The Wall Under Every Comparison Sort

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.

Walk an input down the tree

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.

Say it aloud

H is at least log base two of n factorial.

h
h the height of the tree: the most comparisons the sort makes on any input.
≥
is at least no correct comparison sort can go lower.
log2
log base two of how many doublings it takes to reach a number.
n!
n factorial the number of orders of n keys: 6 for 3 keys, 24 for 4.
In plain words

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.

With numbers

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.

Say it aloud

Log base two of n factorial is about n log base two of n, minus one point four four n.

log2(n!)
log base two of n factorial the floor from the first equation.
≈
is about off by a few units: 3 at n = 10, 11 at n = 1,000,000.
n log2 n
n log base two of n the leading term: it sets the growth.
1.44 n
one point four four n n times log2 e, a smaller correction.
In plain words

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.

With numbers

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.

nFloor ⌈log2(n!)⌉Merge sort, worstInsertion sort, worst
3333
4556
10222545
1,0008,5308,977499,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.

Someone claims a sort that only compares pairs and needs at most 40 comparisons for any 16 keys. Can it be right?

Chapter 2

Counting Sort

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.

  1. Count. For each key v in A, add 1 to C[v].
  2. Running totals. Add each C[v] to the total before it. Now C[v] is how many keys are ≤ v.
  3. Place. Walk A from the right. For each key v, lower C[v] by 1 and put the key at B[C[v]].

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.

Say it aloud

C of v becomes C of v plus C of v minus one.

C[v]
C of v the counter for key value v. Before: how many keys equal v. After: how many are ≤ v.
←
becomes overwrite the counter with the new value.
C[v − 1]
C of v minus one the running total just before, already updated.
In plain words

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.

With numbers

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.

Run counting sort by hand

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.

Say it aloud

T equals two n plus k.

T
T the steps of counting sort. CLRS writes Θ(n + k).
2n
two n one pass over the n keys to count, one to place.
k
k the largest key value: one addition per counter.
In plain words

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.

With numbers

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.

After the running totals, C[3] = 7. Walking from the right, the next key is a 3. Where does it go?

Chapter 3

Radix Sort

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.

Sort seven numbers digit by digit

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).

Say it aloud

T equals d times, open bracket, two n plus k, close bracket.

T
T the steps of radix sort. CLRS writes Θ(d(n + k)), Lemma 8.3.
d
d the number of digits in a key, so the number of passes.
2n
two n each pass counts and places all n keys.
k
k the largest digit: 9 in base 10, 255 in base 256.
In plain words

Run one counting sort per digit. Each costs 2n + k steps. Multiply by d.

With numbers

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.

After the ones pass, 457 comes before 657. Both have 5 in the tens place. Why are they still in that order after the tens pass?

Chapter 4

How Big Should a Digit Be?

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.

Say it aloud

T of r equals the ceiling of b over r, times, open bracket, two n plus two to the r minus one, close bracket.

T(r)
T of r the steps of radix sort with r-bit digits.
⌈b/r⌉
the ceiling of b over r the number of passes: b bits cut into r-bit digits, rounded up.
2n
two n count and place every key, in each pass.
2r − 1
two to the r minus one the largest digit, so the counter additions per pass.
In plain words

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.

With numbers

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.

Pick a digit width

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.

8

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.

You sort a million 64-bit keys. Which digit width gives the fewest steps: 8, 16 or 22 bits?

Chapter 5

Bucket Sort

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.

  1. Key x goes to bucket ⌊n x⌋: with n = 10, 0.78 goes to bucket 7.
  2. Sort each bucket with insertion sort. A bucket holds about one key.
  3. Read the buckets from 0 to n − 1.

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.

Fill the buckets

Each bar is one bucket and its height is how many keys it holds. Switch between even and skewed keys, and change n.

200

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.

Say it aloud

The expected value of n-i squared equals two minus one over n.

E[ ]
the expected value of the average over many random inputs.
ni2
n-i squared the size of bucket i, squared: the insertion sort cost.
2 − 1/n
two minus one over n the variance, 1 − 1/n, plus the mean squared, 1.
In plain words

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.

With numbers

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.

A million keys all fall between 0.50 and 0.51, and you use a million buckets. What happens?

Chapter 6

Stability

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.

Sort the class by score

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.

StableNot 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, TimsortC++ 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).

You sort by score with heapsort, then by name with heapsort. Are students with the same name in score order?

Chapter 7

The Arena

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.

Race six sorts

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.

TryWinnerWhy
Integers 0 to n, n = 1,000Bucket, then countingSmall range: 3,000 counting steps against 8,715 merge sort comparisons
Integers 0 to n³, n = 1,000Bucket, then mergek = 109: counting needs a billion steps
Even reals, any nBucketAbout one key per bucket
Skewed reals, n = 10,000MergeThe 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.

In the arena, why does counting sort lose badly on integers 0 to n³?

Chapter 8

Choose a Sort

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.

Describe your keys

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!).

SortStepsExtra spaceStableNeeds
Merge sortΘ(n log n)nYesOnly a way to compare
HeapsortΘ(n log n)O(1)NoOnly a way to compare
QuicksortΘ(n log n) average, n2 worstlog nNoOnly a way to compare
Counting sort2n + kn + kYesInteger keys 0 to k, k about n or less
Radix sortd(2n + k)n + kYesKeys with d digits
Bucket sortabout 2n average, n2 worstnYes, with insertion sortAn 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.

You must sort 50 million 64-bit integers, stably, with memory to spare. Which sort?

Chapter 9

Field Guide

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.

TermMeaningNumber to remember
Decision treeA comparison sort drawn as yes or no tests3 keys: 6 leaves, height 3
Lower boundFewest worst-case comparisons⌈log2(n!)⌉: 5 for 4 keys, 22 for 10
Counting sortCount, running totals, place from the right2n + k: 21 steps on the 8-key example
Running totalsC[v] = keys ≤ v[2, 0, 2, 3, 0, 1] becomes [2, 2, 4, 7, 7, 8]
Radix sortStable passes, last digit firstd(2n + k): 69 steps for 7 three-digit numbers
Digit widthBits per radix passr = 16 for a million 32-bit keys: 4,131,070 steps
Bucket sortn buckets, insertion sort each, joinE[ni2] = 2 − 1/n
StableEqual keys keep their input orderNeeded by every radix pass

Checklist

The core, as code

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)]

Where it sits

Keep going

The takeaway. A sort is as fast as what it knows. Comparing learns one bit per test, so it needs about n log2 n tests. Knowing the range, the digits or the spread lets you skip the tests.
Which statement is true?

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.

Credit and source

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.

CLRS Chapter 8: Sorting in Linear Time
Next: Order Statistics · Back to Gleams