Counting Steps
Can thinking about an algorithm beat a faster machine?
Seven ledger rows of better machines have left the Job quadratic: its cost per byte rises from about 290 cycles on 10 kB of text to 4,279 on the corpus. The part learns to count steps. It fixes what a step is (the RAM, the word-RAM, the comparison model) and what O, Omega and Theta claim, then sorts: insertion sort with its invariant and its n(n - 1)/4 inversions, merge sort with its recursion tree, and the master theorem that adds such trees up. A decision tree with n! leaves shows that no comparison sort can use fewer than lg n! comparisons, and merge insertion meets that bound up to n = 11 and misses it at 12, 30 against 29. Quicksort's expected 2(n + 1)H_n - 4n comparisons follow from one observation about when two keys are compared, and 10,000 runs show how tightly it concentrates; a first-element pivot on sorted input pays 1,999,000 comparisons where median-of-three pays about 21,000. Counting and radix sort escape the bound by not comparing, median of medians selects in linear time, and generating functions and amortized analysis close the toolkit. The Job, sorted and then counted, makes 103 million key comparisons on the corpus where the search made 15.0 billion, and enters the ledger as row 7.
What you need. Logarithms, sums and proof by induction (Part 2). Expected values are used for quicksort and explained where they appear.
- Mathematics, ideas and history
- models of computation, recurrences and the master theorem, the n log n lower bound, quicksort's 2n ln n, selection, generating functions, amortization
- What we build or compute
- every sort, counted; the Job v1
What you will be able to do
Degree
- State and use O, Omega and Theta, and rank functions by their order of growth.
- Prove insertion sort correct by its loop invariant and count its comparisons through inversions.
- Solve a divide-and-conquer recurrence with a recursion tree or the master theorem, and explain the lg n! lower bound with a decision tree.
Graduate
- Derive quicksort's expected 2(n + 1)H_n - 4n comparisons from the probability 2/(j - i + 1) that two keys are compared.
- Analyse median of medians, T(n) <= T(n/5) + T(7n/10) + O(n), and say why groups of three fail.
- Carry out an amortized analysis of the doubling array by the aggregate, accounting and potential methods.
Research
- State what smoothed analysis measures and what a word-RAM integer-sorting bound assumes about word width and randomness.
- Explain a fine-grained hardness assumption such as SETH or 3SUM and the kind of lower bound it yields.
Industry
- Choose a library sort for given data (presorted runs, small integer keys, stability, data larger than memory) and justify the choice by counts.
- Fit an instruction model to event counts, validate it on held-out inputs, and say what a projection from it does and does not establish.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 24 min · Graduate 43 min · Research 45 min · Industry 29 min.
- 0Can thinking beat silicon?Degree2 min
- 1What counts as a stepGraduate2 min
- 2Orders of growthDegree2 min
- 3Insertion sort and its invariantDegree2 min
- 4Merge sort and the recursion treeDegree2 min
- 5The master theoremDegree3 min
- 6The comparison lower boundDegree4 min
- 7HeapsortDegree2 min
- 8Quicksort, and 2n ln nDegree4 min
- 9How lucky can quicksort get?Graduate2 min
- 10Beating n log nGraduate2 min
- 11Selection and the median of mediansGraduate2 min
- 12Generating functionsGraduate2 min
- 13Amortized analysisGraduate3 min
- 14Sorting in practiceIndustry3 min
- 15The Job, sortedIndustry3 min
- 16Frontier: beyond the worst caseResearch3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Can thinking beat silicon?Degree2 min
This ledger prices the same word-counting task on thirty novels. Act Two improved the machine: pipeline, out-of-order execution, caches and four cores. Act Three added a compiler, a type system and a runtime. These rows combine measured small runs with the stated corpus projections. The best projected time so far is about twelve seconds on four cores. The search algorithm is still the same. Act Four asks how much changing that algorithm can buy.
Here is the search algorithm's growing cost. Version zero keeps distinct words in a list and searches it for each occurrence. The modeled cycles per byte rise across these corpus prefixes. The work depends on both the number of occurrences and the vocabulary: with many distinct words, repeated full scans can take quadratic work. Faster hardware changes the constant. A different data structure or algorithm can change how the work grows.
Here is where we are going. How to count the steps of an algorithm, and which steps to count. Recursion trees, and the master theorem that adds them up. A proof that no algorithm that sorts by comparing can beat n log n, a bound that comes from information. Quicksort's average cost, two n natural log n, derived from one clever observation, and a measurement of how rarely it strays from it. And the Job, sorted instead of searched: ledger row seven.
1What counts as a stepGraduate2 min
An algorithm needs a declared cost model. A RAM gives memory cells addresses and charges for a specified set of instructions: reads, writes, arithmetic, comparisons and jumps. A word-RAM holds w bits per cell. Its word must address the input, so w is at least logarithmic in n; its allowed operations and their word widths are part of the definition. Pebble is a concrete thirty-two-bit example within its address and arithmetic limits. Counting those steps lets us compare algorithms in that model. Seconds still depend on the implementation, memory hierarchy and machine.
Why bound the word size? Starting from three, square the result n times. The answer is three raised to two to the n, with about one point six times two to the n bits. Calling every multiplication one step hides an exponentially growing operand. Here are host Python measurements: the minimum of three same-operand squarings at each step, with the result checked outside the timer. Small values are dominated by timing and interpreter overhead; large values require real multiword arithmetic. No fixed threefold timing ratio is promised. A word-RAM operation handles a bounded number of words. An arbitrary-precision multiplication needs its own cost analysis.
Different questions charge for different resources. A standard logarithmic-word RAM with an effectively simulable instruction set can be simulated by a Turing machine with polynomial overhead. That statement needs bounded operands; it does not grant free arithmetic on arbitrary integers. The comparison model counts comparisons between keys. Its lower bound will assume distinct keys. The cell-probe model charges for memory accesses while allowing free computation between probes, which makes some lower bounds especially strong. The external-memory model counts block transfers between memory levels. Declare the resource before quoting the bound.
2Orders of growthDegree2 min
Asymptotic notation compares eventually nonnegative cost functions. Big O means an eventual constant-factor upper bound, with one fixed constant and one threshold. Omega gives a lower bound; Theta gives both. Little o says the ratio tends to zero when the denominator is positive. Thus three n squared plus a hundred n plus seven is Theta of n squared. This suppresses constants and lower-order terms for the chosen algorithm and model. Changing the algorithm, representation or model can change the growth itself.
The axes now show base-ten logarithms of input size and step count. Powers become straight lines; the exponential bends upward. For the table, assume exactly one nanosecond per abstract step, with no extra overhead. Solve each displayed cost function against one second's budget. The entries are integer maxima, except where explicitly rounded for display. Even a year only permits fifty-four items when the cost is two to the n. A thousandfold speedup expands a quadratic input limit by about thirty-two, and an exponential limit by about ten items. Changing growth can matter much more than changing a constant.
One formula appears again and again when we count arrangements. Stirling's formula says the logarithm of n factorial is n log n minus n, plus a half log of two pi n, plus a term that vanishes. It is astonishingly accurate. At n equals ten the error is about one part in two thousand; at a thousand, about one part in a hundred million. In base two it reads: log of n factorial is n log n minus about one point four four n. Chapter six turns that into the limit on every comparison sort.
3Insertion sort and its invariantDegree2 min
Insertion sort grows a sorted prefix. Save the next key, shift larger keys right, then put the saved key in the gap. Before iteration i, the first i positions contain the original first i elements in sorted order, and the rest of the array is untouched. Watch that prefix grow after each completed insertion. It starts with one element, each iteration preserves the property, and at i equals n it implies the entire output is a sorted permutation. This is induction over a loop; Part 54 will make such proof obligations explicit.
Count the shifts first. An inversion is a pair of positions whose keys are in reverse order. Each shift past the saved key removes one inversion, so there are exactly I shifts. Comparisons are at most I plus n minus one, and total work is Theta of n plus I. For a uniform random permutation of distinct keys, each pair is inverted with probability one half. Linearity of expectation gives n times n minus one over four inversions. The table compares that expectation with finite sample averages, which need not equal it exactly. Sorted input is linear, reverse order is quadratic, and nearly sorted input can make insertion sort useful even though its worst case is quadratic.
One improvement is obvious. The prefix is sorted, so find each new element's place by binary search instead of scanning. The comparisons drop to about n log n. But the elements still have to be shifted to make room, and the shifts are still the inversions: quadratic on average. Whether that matters depends on what a step costs. When comparing is expensive, as with long strings, binary insertion can save cost; expensive movement is not removed. Counting steps always begins with deciding which steps to count. For twelve items it needs thirty-three comparisons in the worst case; chapter six will show that no method can use fewer than twenty-nine.
4Merge sort and the recursion treeDegree2 min
Everything in merge sort rests on one operation. Two lists, each already sorted. Look at the front of each, move the smaller one to the output, and advance in that list. Repeat until one list runs out, then copy the rest of the other. Each comparison places one element, so merging n elements takes at most n minus one comparisons. And if we take from the left list whenever the fronts are equal, equal keys keep their original order. That makes merge sort stable, which the Job will rely on.
Merge sort splits, sorts each half, then merges. We will draw a simple work recurrence, with n a power of two and base cost T of one equal to one. The root pays n for combining. At each internal level the subproblem sizes sum to n, so the level pays n again. There are log base two n internal levels, plus n leaves of unit cost. The sum is n log n plus n. This is the chosen toll model; the exact number of key comparisons is a different count, measured next.
A guessed bound also needs a base case. For this recurrence use c n log n plus n, which covers T of one equal to one. Substitute the bound into the two half-size calls: the extra linear terms leave the inequality true when c is at least one. Our measured sort counts key comparisons instead of charging n at every merge. For powers of two its worst case is exactly n log n minus n plus one. Compare that with the information lower bound in the last column. The gap is linear in n, so the ratio approaches one as n grows.
5The master theoremDegree3 min
Most divide-and-conquer algorithms split a problem of size n into a pieces of size n over b, and spend f of n splitting and combining. The recursion tree has n to the log base b of a leaves, and everything depends on how f compares with that number. If f grows polynomially slower, the leaves dominate and T is Theta of the number of leaves. If f matches it, every level costs the same, and T picks up a log factor: that was merge sort. If f grows polynomially faster, and shrinks geometrically down the tree, the root dominates and T is just Theta of f. Bentley, Haken and Saxe gave the general form in 1980.
Here are the three cases as pictures. Each bar is the total work of one level of the recursion tree, root at the top. Karatsuba's multiplication, three half-size products and linear work: each level costs one and a half times the one above. The sum is dominated by the bottom, the leaves, and the answer is n to the log base two of three, about n to the one point five eight. Merge sort: every level the same, so the sum is a level times the number of levels. And a combine step that costs n squared: each level is half the one above, a geometric series, so the root's n squared is the whole answer, up to a factor of two.
The geometry comes from a geometric series. Let n equal b to the h and retain the leaf term explicitly. Internal level j costs a to the j times f of n over b to the j; the leaves cost a to the h times the base cost. If f is n to the c, consecutive internal levels have ratio a over b to the c. A ratio above one favors the bottom, one gives equal levels, and a ratio below one favors the root. With positive constant base cost, the leaves have the same asymptotic scale as the bottom. The ratio exceeds one exactly when c is less than log base b of a. The theorem formalizes this picture, with its stated regularity conditions.
The table shows the standard three cases. Binary search and merge sort have matching per-level work. Karatsuba and Strassen are leaf dominated; a quadratic combine with two half-size calls is root dominated. For unequal splits, Akra and Bazzi provide a broader method. Our numeric illustration now has explicit integer semantics: for n at most two, T equals n; otherwise split into floor of n over three and the complementary size, and add n. These actual subproblem sizes are memoized separately. The displayed ratio to n log n is a finite numerical check of this example, alongside the asymptotic theorem.
6The comparison lower boundDegree4 min
To prove that no sort can be faster, we need a picture of every possible sort. Run insertion sort on three keys, a, b and c. Its first move is to compare b with a. Depending on the answer it compares something else, and so on, until it knows the order. Draw every possible run as a tree: each node a comparison, each branch an outcome, each leaf the order the sort outputs. Every algorithm that sorts by comparing is such a tree, for each n. Since it must be able to output any of the three factorial, six, orders, it needs at least six leaves. A binary tree of height h has at most two to the h leaves. So some input forces at least the log of six, rounded up, three comparisons. No cleverness can avoid it.
Now assume n distinct keys and a binary comparison model. A correct sort must distinguish n factorial input orders, requiring at least that many leaves. Its worst-case depth is at least log base two of n factorial. Stirling gives n log n minus about one point four four n, plus lower-order terms. Each binary answer supplies at most one bit of information. If all distinct-key permutations are equally likely, the average leaf depth is also at least log n factorial. The distribution matters: a promise that input is already sorted changes the average-case question. In this unrestricted comparison problem, merge sort and heapsort have optimal asymptotic worst-case growth.
How close to the bound can a sort come, for small n? Here are the worst-case comparison counts for sorting three to twelve items. Merge sort and binary insertion fall behind the bound from five items on. Lester Ford and Selmer Johnson's merge insertion, from 1959, pairs the items, sorts the winners, and inserts the losers in a carefully chosen order, so that each binary search runs on a chain of just under a power of two. It meets the information bound exactly for every n up to eleven. We checked our implementation's worst case by running it on every order for n up to eight. At twelve, the bound says twenty-nine, and merge insertion needs thirty. Mark Wells showed in 1965, by exhaustive search, that thirty is the best any algorithm can do. The bound is a floor, not always a door.
An adversary can also prove a lower bound. To find the maximum among distinct items, every other item must lose a comparison: n minus one are necessary and sufficient. Separate scans for minimum and maximum cost nearly twice n. Pair the items first. Search the winners for the maximum and the losers for the minimum; an unpaired item participates in both searches. The count is floor of n over two plus twice ceiling of n over two minus one: ceiling of three n over two minus two, valid for odd and even n. For the lower bound, all but the maximum must lose, and all but the minimum must win. Only comparisons between two untouched items need provide two new facts; the adversary can limit the others to one. At most floor of n over two comparisons join untouched pairs. Counting those facts yields the same bound. Problem three completes the proof.
7HeapsortDegree2 min
A binary heap is a complete binary tree represented by an array. With zero-based indexing, position i has children two i plus one and two i plus two when those positions exist. In this max heap, every parent is at least as large as each child. Check every edge in the displayed example, including the lowest row. The maximum is at the root. For a nonempty heap the height is floor of log base two n; the complete shape supplies that bound.
Inserting n elements one by one would build a heap in n log n. Robert Floyd found a better way. Treat the array as a heap that is wrong everywhere, and fix it from the bottom up: sift each parent down until it is larger than its children. A node at height h costs at most two h comparisons, and only about n over two to the h plus one nodes have that height. The sum of h over two to the h converges to two, so the whole build costs at most two n comparisons: linear. Most nodes are near the bottom, where sifting is cheap. Measured, it costs under two comparisons per element at every size.
Once the heap is built, repeat extraction. Swap the maximum at the root to the end, shrink the active heap, then sift the new root down. There are n minus one rounds, each using at most a logarithmic number of comparisons, so the worst-case count is O of n log n. The table gives our implementation's finite random-input count, including heap construction; its observed constant is not universal. Iterative heapsort needs constant auxiliary storage and is not stable. Its irregular parent-child accesses can hurt locality. Introsort uses heapsort as a worst-case fallback when quicksort's recursion becomes too deep.
8Quicksort, and 2n ln nDegree4 min
Tony Hoare invented quicksort in 1959, as a visiting student in Moscow, and published it in 1961. Pick one element, the pivot. In one pass, compare every other element with it, moving the smaller ones to its left and the larger ones to its right. That costs n minus one comparisons, and afterwards the pivot is in its final place. Then sort the two sides the same way. Unlike merge sort, the work happens before the recursion, and there is nothing to combine.
Hoare's own partition needs no second array. Take the first element as the pivot. One pointer, i, starts at the left and moves right past elements smaller than the pivot; another, j, starts at the right and moves left past larger ones. When both have stopped, each is pointing at an element on the wrong side, so swap them, and continue. When the pointers cross, everything up to j is at most the pivot and everything after it is at least the pivot. It uses no extra memory and makes few swaps, which is part of why quicksort is fast in practice.
Quicksort's average cost has a famously short derivation. Name the elements by their rank in sorted order, z one up to z n, and choose every pivot uniformly at random. Two elements z i and z j are compared at most once, and they are compared exactly when one of them is the first pivot chosen from the range between them. If some element strictly between them is chosen first, they land on opposite sides and never meet. If an element outside the range is chosen, they stay together and wait. So the probability is two out of the j minus i plus one elements in the range. Add over all pairs, and the expected number of comparisons is two times n plus one times the harmonic number, minus four n: about two n natural log n, or one point three nine n log base two n. The leading-term ratio to the information bound approaches one point three nine.
Our measurement uses a declared partition model: one logical comparison with the pivot for every nonpivot key. It does not count individual Python less-than and greater-than instructions. The inputs have distinct keys and pivots are uniform. Each mean averages fifteen or sixty runs, so finite sampling error remains; the displayed exact formula describes the expectation. The leading term is two n natural log n. Its asymptotic ratio to n log base two n is about one point three nine, though lower-order terms matter at these sizes.
Pivot choice changes the risk. On sorted distinct keys, always taking the first key creates sizes zero and n minus one, costing n times n minus one over two partition comparisons. Median of the first, middle and last fixes this particular input. Its pivot-selection comparisons are now counted by the actual three-key sorting routine, not a fixed assigned charge. It still has adversarial inputs. For any fixed distinct-key input, independent uniform random pivots give the same expected count. This assumes the input does not adapt to revealed random choices. Production sorts add cutoffs, duplicate handling and fallback rules. Java's primitive sorts have used dual-pivot quicksort, with details depending on version and type.
9How lucky can quicksort get?Graduate2 min
Before measuring the spread, here is the classical way to get the mean, which uses no clever observation, only algebra. The pivot's rank is uniformly random, so the two sides have sizes k and n minus one minus k for a uniform k, and the expected cost is n minus one plus two over n times the sum of all smaller costs. Multiply by n, and subtract the same equation for n minus one: the sum disappears, leaving a relation between neighbours. Divide by n times n plus one and the relation telescopes. Summing it gives the same exact answer as before, two times n plus one times H n, minus four n. Two proofs, one number.
A mean does not describe every run. Here we sort the same thousand distinct keys ten thousand times, using a separate deterministic seed for each sequence of uniform pivots. The histogram counts runs in each comparison interval. The sample mean is close to the exact expectation. The sample standard deviation is about zero point six four n. The displayed theoretical coefficient is the large-n limit, not an exact finite-n standard deviation. Relative to a mean growing like n log n, this spread eventually shrinks. The largest observed count is far below the possible quadratic worst case. A finite sample illustrates that difference; it cannot eliminate rare outcomes.
Read the measured tail frequencies directly from the table. These are fractions of ten thousand runs above the sample mean plus one, two, three or four sample standard deviations. The four-deviation frequency in this sample is two in a thousand. For fixed positive relative deviations, classical quicksort tail bounds decay faster than any inverse fixed power of n, asymptotically. That theorem assumes the classical distinct-key model and uniform random pivots. It gives a probabilistic guarantee, not impossibility of a slow finite run. Part 20 develops the probability tools behind such claims.
10Beating n log nGraduate2 min
The comparison lower bound restricts which operations reveal information. Integer algorithms may inspect digits and index arrays instead. Counting sort handles keys from zero through k minus one in O of n plus k time, with O of k counters. Least-significant-digit radix sort applies a stable distribution pass to each digit. Order from earlier digits survives ties in later passes. For fixed thirty-two-bit keys and eight-bit digits, four passes suffice; the bound includes the digit counters. Punched-card equipment made digit-by-digit organization a physical operation, long before modern computers. For growing word widths, linear time is a different question. Historical word-RAM bounds depend on the instruction set, randomization and the relation between word width and input size.
Watch seven three-digit keys pass through a textbook radix sort. The first stable pass orders the units. The second orders the tens, preserving units order among equal tens. The third orders the hundreds while preserving the lower two digits' order among ties. The final order is sorted. The invariant after each pass is order by the suffix of digits processed so far. That stability condition is essential; an arbitrary unstable digit sort would not establish it.
These are checked host measurements, not a universal ranking. C qsort, C++ std::sort and our radix sort receive the same deterministic thirty-two-bit input. Each result is validated outside the timer against a full sorted reference. The separate counting-sort column masks that source to sixteen bits, so it solves a smaller-domain problem. Each displayed time is the minimum of three runs at that size. Input copies and reference checks are excluded; counting-sort counter allocation is included. Read the observed ratios from the table, with the compiler versions and protocol below. Key width, extra storage, cache state and implementation all affect the result. Comparison sorts remain useful for general ordered objects.
11Selection and the median of mediansGraduate2 min
Selection needs one rank, not every rank. Quickselect partitions around a pivot and continues only in the side containing the requested rank. Our count charges one logical partition comparison per nonpivot key. For distinct keys and a uniform pivot, the expected larger side is at most three quarters of the current size. Bounding the chosen side by that larger side gives a crude linear bound, about four n; it is an expectation argument, not a guaranteed shrink at each step. For the median, the leading expected term is two plus two natural log two, times n, with lower-order corrections. The finite sample means need not equal that asymptotic coefficient exactly.
We can guarantee linear worst-case work. Divide distinct keys into groups of five and sort each small group to find its median. Every less-than comparison in that routine is now counted. Recursively select the median of those medians as the pivot. In the picture, at least half the group medians lie on either side. Each such full group contributes three keys on the corresponding side, apart from the pivot group and a possible incomplete group. This gives three n over ten minus a constant protected on each side. The recurrence therefore uses a ceiling for the medians call and seven n over ten plus a constant for the remaining side. The fractions sum to nine tenths, so a sufficiently large linear bound closes by induction. The displayed finite implementation count is an example, not a universal comparison constant.
The group size changes what this proof can establish. With groups of three, the elementary upper-bound recurrence has fractions one third and two thirds. Their sum is one, giving an O of n log n bound by this argument. With five, one fifth plus seven tenths is less than one, so a linear toll gives a linear upper bound after accounting for rounding. Seven also gives a sum below one, with a different small-group cost. This shrinking-sum test applies to these linear-toll recurrences. It is not a universal characterization of all divide-and-conquer algorithms.
12Generating functionsGraduate2 min
Recurrences like quicksort's are often solved by a trick from the eighteenth century: turn the whole sequence into one function. Make the Fibonacci numbers the coefficients of a power series, F of z. The recurrence, each term the sum of the two before, becomes an equation about the function itself: F equals z plus z F plus z squared F. Solve it like algebra: F is z over one minus z minus z squared, and partial fractions split it into two geometric series. Read off the coefficient, and out comes Binet's formula, with the golden ratio. We checked it against the recurrence for every n up to sixty-one.
Now count ordered binary trees with empty subtrees allowed. With n nonempty nodes, their counts begin one, one, two, five, fourteen, forty-two. A tree is empty, or a root with an ordered left and right subtree. Thus C equals one plus z C squared. Choose the solution with C of zero equal to one, and its coefficients give the Catalan formula. The nearest singularity is at one quarter. Its location gives the exponential base four; its square-root form supplies the n to the minus three halves factor. Location alone would not determine that power. Together they give four to the n over square root of pi times n to the three halves. The displayed finite ratios approach one, illustrating the asymptotic result.
13Amortized analysisGraduate3 min
Java's ArrayList, C++'s vector and Python's list all grow geometrically. Take the simplest rule, doubling. Most appends cost one step. But when the array is full, it allocates one twice as big and copies everything across: an append that costs as much as all the elements so far. The worst single append is linear. Yet the expensive ones come at sizes one, two, four, eight, and the copies add up to less than two n. Averaged over any sequence of appends, the cost is at most three per append. That is an amortized bound: not an average over random inputs, but a guarantee for every sequence.
The second standard example is a binary counter. Adding one flips the trailing ones to zeros, and the next zero to one. Counting from fifteen to sixteen flips five bits; in general, the worst increment flips them all. But the lowest bit flips every time, the next every second time, the next every fourth. Over n increments the total is less than two n, and the running total in the last column never catches up with twice the count. As a potential argument: let the potential be the number of ones. An increment that flips t ones to zero and one zero to one costs t plus one and lowers the potential by t minus one, so its amortized cost is two.
Three proofs describe the same guarantee. Aggregate the copies: one plus two plus four, up to the last full capacity, is less than twice the number of appends. Include the insertions and the total is below three n. Accounting charges three units per append and saves the unused credit for later copying. For a potential proof starting from size zero and capacity one, use the maximum of zero and twice the size minus capacity. This potential starts at zero and stays nonnegative. Actual cost plus its change is at most three for every append, including the first. Summing cancels the intermediate potentials, giving a bound for every append sequence, without an input distribution.
A fixed growth factor greater than one gives constant amortized copying cost. Our million-append examples compare factors two and one point five, including integer rounding. The smaller factor copies more often. The last row only tests aggregate freed size. For doubling, all previously freed blocks together are too small for the next request. Below the golden ratio, their total can eventually be large enough. Libraries choose growth policies under these competing costs, and the exact policy depends on implementation and version.
14Sorting in practiceIndustry3 min
Existing order is useful information. We count comparisons made by this Python interpreter's sorted function through a comparison wrapper. These are comparison counts, not elapsed times. One input uses exactly a thousand random transpositions of an initially sorted hundred-thousand-element array; that is not exactly one percent of positions shuffled. Python's sort detects natural runs, extends short runs and merges them. Current measurements here use the interpreter reported on screen; its modern merge policy is powersort, within the Timsort family. Implementations evolve. Rust changed both standard sorting implementations in version one point eight one, so the old Timsort and pattern-defeating quicksort labels should not be read as current Rust guarantees. Go's inspected sort source uses a pattern-defeating quicksort variant with a heapsort fallback.
The historical Timsort bug shows why an invariant must hold everywhere it is needed. The old merge policy intended run lengths to grow fast enough down the pending stack to keep its height logarithmic. In 2015, de Gouw and colleagues found that local repairs near the top did not always restore the required invariant deeper down. Their verification work led to a constructed input that exhausted the allocated Java run stack. Implementations adopted repairs, and merge policies later evolved; this is a historical case study, not a claim that the measured modern Python sort still has that failure. Part 54 returns to the role of machine-checked proofs.
Sorting a file larger than memory changes what is expensive. Read as much as fits, sort it, and write it back as a sorted run. Then merge many runs at once, keeping one block of each in memory and a heap to pick the smallest head. A classic trick makes the runs longer than memory. Replacement selection keeps a heap of M records: output the smallest, read the next record, and if it is still at least the last output, it joins the current run. Knuth showed that on random input the runs average two M. Ours, with a thousand records of memory, made runs averaging two thousand. On sorted input it makes one run: the whole file. Fewer runs means fewer passes over the disk, which is the cost that matters in the external-memory model, and in every database's sort.
15The Job, sortedIndustry3 min
Version one sorts occurrences, then counts equal runs. Each occurrence records its letters' start and length. A stable bottom-up merge sort orders them by letters. Equal words become neighbors; stability preserves the first occurrence needed for tie breaking. Selecting the twenty largest counts therefore reproduces version zero's output. For the corpus projection, we enlarge the arrays explicitly and use that same compiled image for calibration passages and core samples. Their outputs are checked against the reference. The whole corpus is counted by the native event model; it is not fully executed on the emulator.
Separate exact event counts from projected runtime. The native model follows the sort-and-count control flow on the full corpus and checks the final word-count output. In version zero, the corrected letter-comparison count includes matched prefixes and the first mismatch; a same-length table entry is not itself one letter comparison. We fit instruction counts from thirty actual emulator passages and test ten held-out passages. The displayed maximum error applies only to those tests, not every possible text. Applying the fit to corpus events estimates instructions. Dividing by IPC measured on three core passages estimates cycles, then time at the stated clock. Neither corpus instructions nor its IPC has been measured by a full-corpus core run.
A fitted decomposition suggests where to investigate. These bars group coefficient times corpus event count, not traced instruction categories. Correlated features can admit different coefficient allocations with similar total predictions. The copy-back term motivates a concrete experiment: alternate the two arrays instead of copying a full pass back. That needs a changed program, checked output and a new measurement. Use the model to propose and test an optimization, while keeping attribution uncertainty visible.
The ledger gains an explicitly projected row. It combines full-corpus event counts, the held-out instruction fit and passage-sampled IPC on one modeled core. Its arrays and emulated memory are sized for the corpus, while the full corpus remains unexecuted on that core. Read the estimated time and speedups on screen. They compare the stated models and assumptions; they are not elapsed timings of full-corpus runs. The important algorithmic change is replacing repeated vocabulary scans with sorting. Part 17 asks whether hashing can remove that sorting step too.
16Frontier: beyond the worst caseResearch3 min
Worst-case and average-case analysis ask different questions. This experiment starts with one sorted input of two thousand keys, adds independent Gaussian noise with the shown standard deviation, and averages ten seeded trials per noise level. For this input family, the observed first-pivot comparison count falls toward the random-order benchmark. It does not show that every real input is harmless, or that every noisy trial improves. Formal smoothed analysis takes a worst case over the permitted initial inputs, then an expectation over the specified perturbation. Spielman and Teng developed the framework for simplex. Our single-family plot illustrates the idea; it does not compute that worst-case smoothed bound.
Integer sorting depends on the precise machine model. The table collects historical word-RAM upper bounds, with their randomization and word-width conditions. Reading digits escapes the comparison lower bound, but fixed thirty-two-bit radix sort does not settle the asymptotic question for every growing word width. The author abstracts for the listed linear-time results require sufficiently large words; some results are expected-time randomized bounds. Our research question asks how such restrictions can be relaxed in an explicitly specified instruction model. These selected historical sources are not a complete survey of every recent result.
Some frontiers concern the exponent itself. Fine-grained complexity studies conditional statements under precisely stated conjectures: satisfiability, three-sum, and weighted all-pairs shortest paths, in their respective models. The forbidden improvements are by a fixed power, not necessarily by logarithmic factors. Backurs and Indyk's edit-distance reduction says that a truly subquadratic algorithm would refute the relevant strong exponential-time hypothesis. This is conditional evidence, not an unconditional quadratic lower bound or a proof that every conjecture is equivalent. Reductions connect specific versions of problems. Their alphabet, weights, randomization and computational model matter.
Here are research directions, each needing a precise statement. Can integer-sorting bounds be improved across word widths, with a fixed permitted instruction set and a stated randomness guarantee? What are the exact optimal comparison counts beyond the small cases we checked? Which specific fine-grained conjectures admit reductions to each other? And which beyond-worst-case input models predict a chosen real workload well enough to test? The starred exercise starts by fixing a word-RAM model and checking the restrictions of known results, then proposing an extension or a reproducible finite experiment.
Recap, problems, and where this comes backAll tracks3 min
We built a toolkit for counting the resource that matters. Invariants establish sorted output. Recursion trees turn repeated work into a sum, with base costs retained. Comparison trees bound sorting distinct keys; random pivots produce an analyzable distribution. Reading digits changes the model, selection avoids sorting all ranks, generating functions expose coefficients, and amortized analysis bounds whole sequences. The revised Job replaces repeated scans with a stable sort. Its ledger improvement is a checked projection, with corpus counts, fitted instructions and sampled IPC kept separate.
Where this comes back. Part 17 replaces the sort with a hash table, for ledger row eight. Part 18's graph algorithms run on heaps. Part 19 generalizes divide and conquer, and adds dynamic programming. Part 20 builds the probability tools that chapter nine only previewed. Part 21 sorts all the suffixes of a text to search it. Part 26 asks which lower bounds can be proved at all. Part 35's database sorts and joins tables larger than memory, and Part 39's MapReduce is, at heart, a distributed sort.
In practice, know your library sort's stability, key interface and worst-case contract. When reviewing nested loops, sum their actual iteration counts: nested syntax alone does not imply quadratic work. Two-pointer scans or shrinking bounds can change the total. Database sorting may use in-memory or external algorithms depending on the plan and data size. Measure representative inputs, check the output, record the protocol, and distinguish an asymptotic bound from a finite timing.
The notes contain four worked analysis problems, a radix-sort build plan, and a research starting point. The counting exercises state their distinct-key and random-pivot assumptions. The build problem requires an implemented program, correct output and measured instruction counts. The starred direction first fixes word width, instructions and randomness, then checks what the cited results already establish before proposing an extension. It is not presented as a solved exercise.
Next time: dictionaries. Insert a word, look it up, add one. Hashing gives expected constant probes under its hash and load assumptions; reading and hashing a string still costs its letters. Balanced search trees bound the number of comparisons logarithmically. With union by rank and path compression, union-find has an inverse-Ackermann amortized bound over operation sequences. Part 17, Data Structures, develops those guarantees and their conditions.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 17 replaces the sort with a hash table for ledger row 8, and Part 18's graph algorithms run on this part's heaps. Part 19 generalizes divide and conquer and adds dynamic programming, Part 20 builds the probability tools that the concentration chapter previews, Part 21 sorts the suffixes of a text, Part 26 asks which lower bounds can be proved at all, and Part 35's database sorts tables larger than memory.
Key results
The part's results in one place, for revision.
Try it
Lab 16 · Counting comparisons: the lower bound, and quicksort's average
With the series' instrumented sorts, find the worst case of three algorithms over every permutation of up to seven keys and compare it with the decision-tree bound; run randomized quicksort 400 times on 1,000 keys and compare its mean and spread with the formulas; then give two pivot rules a sorted input.
python -m videos.cs.labs 16
needs numpy, scipy, matplotlib · download lab16.py ·
source on GitHubworst case over all 120 orders of 5 keys bound 7 merge insertion 7 merge sort 8 insertion sort 10
worst case over all 720 orders of 6 keys bound 10 merge insertion 10 merge sort 11 insertion sort 15
worst case over all 5,040 orders of 7 keys bound 13 merge insertion 13 merge sort 14 insertion sort 21
merge insertion against the bound at n = 12 30 comparisons, bound 29
quicksort, 400 runs on 1,000 keys: mean 11,004 (2(n + 1)H_n - 4n = 10,986)
its standard deviation 642 (large-n theory 0.648 n = 648)
fewest and most comparisons 9,784 and 13,903 (lg n! = 8,530, n(n - 1)/2 = 499,500)
sorted input, 2,000 keys first-element pivot 1,999,000 median of three 20,010 (n(n - 1)/2 = 1,999,000)
No comparison sort can beat lg n! in the worst case, and merge insertion meets it for small n; randomized quicksort averages 2n ln n on every input and rarely strays, while a fixed pivot rule has inputs that cost n²/2.
The code (95 lines; it asserts its own result)
"""Lab 16: count the comparisons of every sort, against the lg n! lower bound and quicksort's 2(n + 1)H_n - 4n."""
from videos.coursekit import labs
import math
import random
import numpy as np
from explainer.cs.algo import sorts
TITLE = "Counting comparisons: the lower bound, and quicksort's average"
GOAL = ("With the series' instrumented sorts, find the worst case of three algorithms over every permutation of up "
"to seven keys and compare it with the decision-tree bound; run randomized quicksort 400 times on 1,000 "
"keys and compare its mean and spread with the formulas; then give two pivot rules a sorted input.")
TASKS = [
"Add sorts.heapsort to the worst-case table. How far above the bound is it at n = 7, and does sorts.binary_insertion_sort do better than insertion sort?",
"Call sorts.quicksort(xs, 'first') on 2,000 keys of which only 20 random pairs have been swapped out of sorted order. How close to n(n - 1)/2 does it stay?",
"Count comparisons of sorts.quickselect for the median of 1,000 keys over 400 runs and compare the mean with (2 + 2 ln 2) n.",
]
RUNS, N = 400, 1000
def run(seed=0):
rng = np.random.default_rng(seed)
pyrng = random.Random(seed)
lab = labs.Lab()
# 1. the decision-tree bound against exhaustive worst cases
for n in range(2, 8):
bound = sorts.lower_bound(n)
worst = {name: sorts.worst_case(f, n) for name, f in (("merge insertion", sorts.ford_johnson),
("merge sort", sorts.merge_sort),
("insertion sort", sorts.insertion_sort))}
assert all(w >= bound for w in worst.values()), f"a comparison sort beat lg {n}!"
assert worst["merge insertion"] == bound == sorts.ford_johnson_formula(n), "merge insertion is optimal here"
assert worst["insertion sort"] == n * (n - 1) // 2
if n >= 5:
lab.row(f"worst case over all {math.factorial(n):,} orders of {n} keys",
f"bound {bound} merge insertion {worst['merge insertion']} merge sort {worst['merge sort']}"
f" insertion sort {worst['insertion sort']}")
gap = [(n, sorts.ford_johnson_formula(n), sorts.lower_bound(n)) for n in range(2, 13)]
assert all(f == b for _, f, b in gap[:-1]) and gap[-1][1:] == (30, 29), "the bound is met to n = 11, not at 12"
lab.row("merge insertion against the bound at n = 12", f"{gap[-1][1]} comparisons, bound {gap[-1][2]}")
# 2. randomized quicksort on N distinct keys
keys = rng.permutation(N).tolist()
counts = np.array([sorts.quicksort(keys, "random", rng=pyrng)[1]["cmp"] for _ in range(RUNS)])
expect = sorts.quicksort_expected(N)
sigma = math.sqrt(7 - 2 * math.pi ** 2 / 3) * N # the large-n standard deviation
lab.row(f"quicksort, {RUNS} runs on {N:,} keys: mean", f"{counts.mean():,.0f} (2(n + 1)H_n - 4n = {expect:,.0f})")
lab.row("its standard deviation", f"{counts.std(ddof=1):,.0f} (large-n theory 0.648 n = {sigma:,.0f})")
lab.row("fewest and most comparisons", f"{counts.min():,} and {counts.max():,} "
f"(lg n! = {sorts.lower_bound(N):,}, n(n - 1)/2 = {N * (N - 1) // 2:,})")
assert abs(counts.mean() / expect - 1) < 0.015, "the mean should be 2(n + 1)H_n - 4n"
assert 0.8 < counts.std(ddof=1) / sigma < 1.2, "the spread should be about 0.65 n"
assert counts.min() >= sorts.lower_bound(N) and counts.max() < 2 * expect
# 3. a sorted input: the first element as pivot, and the median of three
n = 2000
first = sorts.quicksort(list(range(n)), "first")[1]["cmp"]
med3 = sorts.quicksort(list(range(n)), "median3")[1]["cmp"]
lab.row(f"sorted input, {n:,} keys", f"first-element pivot {first:,} median of three {med3:,} "
f"(n(n - 1)/2 = {n * (n - 1) // 2:,})")
assert first == n * (n - 1) // 2 and med3 < 2.2 * n * math.log2(n)
lab.note = ("No comparison sort can beat lg n! in the worst case, and merge insertion meets it for small n; "
"randomized quicksort averages 2n ln n on every input and rarely strays, while a fixed pivot rule "
"has inputs that cost n²/2.")
fig, ax = labs.figure(2, size=(11, 4.4))
ns = np.array([16, 32, 64, 128, 256, 512, 1024])
series = {"insertion sort": [], "merge sort": [], "quicksort (random pivot)": []}
for n in ns:
xs = rng.permutation(int(n)).tolist()
series["insertion sort"].append(sorts.insertion_sort(xs)[1]["cmp"])
series["merge sort"].append(sorts.merge_sort(xs)[1]["cmp"])
series["quicksort (random pivot)"].append(np.mean([sorts.quicksort(xs, "random", rng=pyrng)[1]["cmp"]
for _ in range(5)]))
grid = np.geomspace(16, 1024, 60)
lgfact = np.array([math.lgamma(n + 1) / math.log(2) for n in grid])
ax[0].fill_between(grid, 1, lgfact, color=labs.RED, alpha=0.12)
ax[0].plot(grid, lgfact, color=labs.RED, label="lg n! (nothing sorts below this)")
ax[0].plot(grid, grid * (grid - 1) / 4, color=labs.GREY, ls="--", label="n(n - 1)/4")
for (name, ys), color in zip(series.items(), (labs.ORANGE, labs.GREEN, labs.BLUE)):
ax[0].plot(ns, ys, "o-", color=color, ms=4, lw=1.2, label=name)
ax[0].set(title="Comparisons to sort n random keys", xlabel="n", ylabel="comparisons", xscale="log", yscale="log",
ylim=(30, None))
ax[0].legend()
ax[1].hist(counts, bins=40, color=labs.BLUE, alpha=0.7, label=f"{RUNS} runs")
ax[1].axvline(expect, color=labs.GOLD, label="2(n + 1)H_n - 4n")
ax[1].axvline(sorts.lower_bound(N), color=labs.RED, label="lg n!")
ax[1].axvspan(expect - sigma, expect + sigma, color=labs.GOLD, alpha=0.12, label="± 0.648 n")
ax[1].set(title=f"Randomized quicksort on {N:,} keys", xlabel="comparisons", ylabel="runs")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Add sorts.heapsort to the worst-case table. How far above the bound is it at n = 7, and does sorts.binary_insertion_sort do better than insertion sort?
- Call sorts.quicksort(xs, 'first') on 2,000 keys of which only 20 random pairs have been swapped out of sorted order. How close to n(n - 1)/2 does it stay?
- Count comparisons of sorts.quickselect for the median of 1,000 keys over 400 runs and compare the mean with (2 + 2 ln 2) n.
Problems, with solutions
Try each problem before opening its solution.
-
Insertion sort's cost. For n ≥ 1 and distinct keys, show that insertion sort makes at most I + n − 1 comparisons, where I is the number of inversions, and that E[I] = n(n − 1)/4 for a uniformly random permutation of those distinct keys.
Solution
In the inner loop for element i, each comparison either finds a larger element, which is then shifted one place right, or ends the loop. A shift exchanges an adjacent inverted pair, removing exactly one inversion and creating none, so there are exactly I shifts in all, and at most one loop-ending comparison per i: at most I + n − 1 comparisons. For a random order, each of the n(n − 1)/2 pairs is inverted with probability 1/2 by symmetry (reversing the pair's relative order is a bijection between orders), so by linearity of expectation E[I] = n(n − 1)/4. (
compute.py'sinsertionitem measures both.) -
Between the cases. For n = 2^h and positive constant T(1), solve T(n) = 4T(n/2) + n² lg n with a recursion tree.
Solution
Level j has 4ʲ subproblems of size n/2ʲ, costing 4ʲ (n/2ʲ)² lg(n/2ʲ) = n² (lg n − j). Summing over j = 0, …, lg n gives n² (lg n + (lg n − 1) + ⋯ + 0) = n² lg n (lg n + 1)/2 = Θ(n² log² n). This is the internal combine sum; add the n² leaves at constant base cost, which does not change the asymptotic answer. Here f(n) = n^{log_b a} lg n exceeds n^{log_b a} but not by a polynomial factor, so neither case 2 nor case 3 of the basic theorem applies; the extended case 2 (f = Θ(n^{log_b a} logᵏ n) gives Θ(n^{log_b a} log^{k+1} n)) agrees.
-
Minimum and maximum. For n ≥ 1 distinct items, prove that finding both the minimum and the maximum of n items needs ⌈3n/2⌉ − 2 comparisons, and give an algorithm that uses exactly that many.
Solution
Algorithm: compare the items in pairs (⌊n/2⌋ comparisons), then find the maximum of the winners and the minimum of the losers (with an odd item joining both groups), ⌈n/2⌉ − 1 comparisons each: ⌈3n/2⌉ − 2 in all. Lower bound: say an item has won if it was ever larger in a comparison and lost if ever smaller. At the end, every item but the maximum must have lost and every item but the minimum must have won: 2n − 2 units of information. A comparison between two untouched items gives two units; the adversary answers every other comparison so as to give at most one (it can always keep its answers consistent by treating winners as large and losers as small). At most ⌊n/2⌋ comparisons are between untouched items, so the number of comparisons is at least ⌊n/2⌋ + (2n − 2 − 2⌊n/2⌋) = ⌈3n/2⌉ − 2 (Pohl 1972).
-
Quickselect for the minimum. With distinct keys, independent uniform pivots and one logical comparison per nonpivot per partition, show that quickselect, asked for the minimum, makes 2n − 2Hₙ comparisons on average.
Solution
After n − 1 comparisons the pivot has a uniform rank r; if r = 1 we are done, otherwise we recurse on the r − 1 smaller items. So Cₙ = n − 1 + (1/n) Σ_{k=0}^{n−1} C_k. Multiplying by n and subtracting the same equation for n − 1 gives nCₙ − (n − 1)C_{n−1} = 2(n − 1) + C_{n−1}, that is Cₙ = C_{n−1} + 2 − 2/n. With C₁ = 0, summing gives Cₙ = 2n − 2Hₙ: about twice the n − 1 of a plain scan.
-
Build: radix sort for the Job. Rewrite the Job v1 with a radix sort on letters, in the Pebble language, and compare its instruction count with the merge sort on our passages.
Solution
Solution sketch. Use most-significant-digit radix sort with 27 buckets per level (end of word, then a to z): count the occurrences in each bucket, compute offsets, distribute stably into a scratch array, then recurse into each bucket on the next letter, switching to insertion sort for buckets smaller than about 16. Each examined prefix letter, including the terminating bucket when needed, is read a constant number of times per distribution level. This replaces repeated full-key comparisons with prefix work; duplicate words still require processing through their terminators. The exact work must be counted in the implemented program; but every recursion level pays for its 27 counters, which dominates on small passages. Compute the distinguishing-prefix total for the corpus with a variant of
FEATURES_C, fit the new program's instruction count as injob.py, and compare: the crossover between merge sort and radix sort is the answer. -
★ Research: integer sorting with a specified model. Fix the allowed instructions, word width as a function of n, space budget and randomization guarantee. Identify a restriction in a cited linear-time result and propose a precise extension or a lower-bound target. A finite 32-bit radix/comparison experiment is a separate reproducible build task, not a resolution of the growing-word-width problem.
Where to start. Upper bounds: Fredman and Willard's fusion trees (1990) first beat n log n; Andersson, Hagerup, Nilsson and Raman (1995) sort in O(n log log n), and in randomized expected linear time when the word length is at least log^{2+ε} n; Han and Thorup (2002) reach O(n √(log log n)) expected; Belazzougui, Brodal and Nielsen (2014) give expected linear time for words of Ω(log² n log log n) bits. Lower bounds: none superlinear is known for sorting on the word-RAM; strong bounds exist in restricted models (comparisons, and AC⁰ instruction sets) and for related problems such as predecessor search (Pătraşcu and Thorup 2006). Use these as historical starting points: selected author/university abstracts were checked, not every proof or every recent result. Reconcile the operation set and randomness assumptions before stating what an extension would improve. Keep a finite 32-bit measurement separate from a theorem for all word widths.
Notes and sources
Glossary
步数 step count · 计算模型 model of computation · 随机存取机 RAM · 字 RAM word-RAM · 单位代价 unit cost · 细胞探测模型 cell-probe model · 外存模型 external-memory model · 渐近记号 asymptotic notation · 大 O / Ω / Θ / 小 o big O / Omega / Theta / little o · 斯特林公式 Stirling's formula · 循环不变式 loop invariant · 逆序对 inversion · 插入排序 insertion sort · 二分插入 binary insertion · 归并排序 merge sort · 稳定 stable · 递归树 recursion tree · 代入法 substitution method · 主定理 master theorem · 决策树 decision tree · 比较下界 comparison lower bound · 对手论证 adversary argument · 归并插入 merge insertion · 堆 heap · 堆排序 heapsort · 堆化 heapify · 内省排序 introsort · 快速排序 quicksort · 枢轴 pivot · 划分 partition · 双枢轴 dual pivot · 集中性 concentration · 尾部界 tail bound · 计数排序 counting sort · 基数排序 radix sort · 快速选择 quickselect · 中位数的中位数 median of medians · 生成函数 generating function · 卡特兰数 Catalan numbers · 解析 组合 analytic combinatorics · 奇点 singularity · 摊还分析 amortized analysis · 势函数 potential function · 动态数组 dynamic array · 增长因子 growth factor · 外部归并排序 external merge sort · 置换选择 replacement selection · 平滑分析 smoothed analysis · 细粒度复杂性 fine-grained complexity · 强指数时间假说 strong exponential time hypothesis (SETH)
Sources
Canon. Books: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, chapters 1–9, 16–17; Knuth, The Art of Computer Programming, volume 3, Sorting and Searching; Sedgewick & Flajolet, An Introduction to the Analysis of Algorithms; Graham, Knuth & Patashnik, Concrete Mathematics; Flajolet & Sedgewick, Analytic Combinatorics (2009); Kleinberg & Tardos, Algorithm Design; Erickson, Algorithms.
Papers: Ford & Johnson, "A tournament problem" (1959); Hoare, "Algorithm 64: Quicksort" (1961) and "Quicksort" (1962); Williams, "Algorithm 232: Heapsort" (1964); Floyd, "Algorithm 245: Treesort 3" (1964); Wells (1965); Pohl, "A sorting problem and its complexity" (1972); Blum, Floyd, Pratt, Rivest & Tarjan, "Time bounds for selection" (1973); Knuth, "Big Omicron and big Omega and big Theta" (1976); Bentley, Haken & Saxe, "A general method for solving divide-and-conquer recurrences" (1980); Tarjan, "Amortized computational complexity" (1985); Aggarwal & Vitter, "The input/output complexity of sorting and related problems" (1988); McDiarmid & Hayward, "Large deviations for Quicksort" (1996); Akra & Bazzi, "On the solution of linear recurrence equations" (1998); Peters, "listsort.txt" (2002); Yaroslavskiy, dual-pivot quicksort (2009); de Gouw, Rot, de Boer, Bubel & Hähnle, "OpenJDK's java.utils.Collection.sort() is broken" (2015); O. Peters, "Pattern-defeating quicksort" (2021).
Frontier. Spielman & Teng, "Smoothed analysis of algorithms" (2001); Banderier, Beier & Mehlhorn, "Smoothed analysis of three combinatorial problems" (2003); van Emde Boas (1975); Fredman & Willard, fusion trees (1990); Andersson, Hagerup, Nilsson & Raman, "Sorting in linear time?" (1995); Han & Thorup, "Integer sorting in O(n √(log log n)) expected time and linear space" (2002); Belazzougui, Brodal & Nielsen (2014); Backurs & Indyk, "Edit distance cannot be computed in strongly subquadratic time (unless SETH is false)" (2015); Williams, "On some fine-grained questions in algorithms and complexity" (2018).
About this partfrom its README
Part 16 of a sixty-one-part course in computer science (see the series plan and
the syllabus), opening Act IV, Algorithms. Seven ledger rows of better machines left the Job
quadratic; this part learns to count steps, proves what sorting must cost, and sorts the Job. The instruments are
explainer/cs/algo/sorts.py (insertion, binary insertion, merge, heap, quick with three pivot rules, Ford–Johnson
merge insertion, counting and radix sort, Python's Timsort counted through a key wrapper, quickselect, median of
medians, decision trees, the dynamic array, replacement selection, with explicitly defined key-comparison counters) and
explainer/cs/algo/job.py (the Job v1, sort then count, in the Pebble language; an exact simulator of its control
flow that counts 24 events; a least-squares model of its instruction count; and a C program that counts the same
events on all thirty novels), tested in tests/test_cs16_sorts.py. Every number is computed in compute.py;
ram and linear time code on this machine; practice counts comparisons through a wrapper.
- Can thinking beat silicon? The ledger so far; the Job v0's cost per byte rising from about 290 cycles on 10 kB to 4,279 on the corpus.
- 1. What counts as a step. The RAM and the word-RAM; repeated squaring timed in the actual host interpreter (minimum of three, result checked; no fixed timing ratio); Turing machines, the comparison model, cell probes, external memory.
- 2. Orders of growth. O, Ω, Θ and o; the ladder on log–log axes; the largest n solvable at a nanosecond a step; Stirling's formula checked.
- 3. Insertion sort and its invariant. The invariant animated; inversions, n(n − 1)/4 derived and measured; binary insertion, fewer comparisons and the same moves.
- 4. Merge sort and the recursion tree. Merging animated; the tree for 2T(n/2) + n; the substitution method; comparisons against n lg n and the lower bound.
- 5. The master theorem. The three cases; their geometry as level-by-level bars (Karatsuba, merge sort, a heavy combine); the geometric-series proof; five recurrences; an explicit floor/complement integer example alongside Akra–Bazzi.
- 6. The comparison lower bound. The decision tree of insertion sort on three keys; lg n! and information; min-and-max by adversary (⌈3n/2⌉ − 2); merge insertion meets the bound for n ≤ 11, and 30 > 29 at n = 12.
- 7. Heapsort. The heap in an array; Floyd's linear heapify (Σ h/2ʰ = 2, under 2 comparisons per element measured); heapsort's 1.8 n lg n; introsort.
- 8. Quicksort, and 2n ln n. Partition; Hoare's two pointers animated; the 2/(j − i + 1) argument; the exact mean measured; pivot rules on sorted input (1,999,000 against about 21,000); dual pivot.
- 9. How lucky can quicksort get? The recurrence solved by telescoping; 10,000 runs: σ = 0.639 n against the large-n theoretical coefficient 0.648 n; the tails; McDiarmid and Hayward.
- 10. Beating n log n. Counting and radix sort; radix sort animated; timed with full reference-output checks, a common 32-bit source and a separate 16-bit counting domain; integer sorting on the word-RAM.
- 11. Selection and the median of medians. Quickselect (finite sample mean versus its 3.39 n asymptotic leading term); why groups of five; median of medians with actual group-sort tests plus logical partition comparisons (8.29 n in the largest displayed sample).
- 12. Generating functions. Fibonacci and Binet; Catalan numbers from a quadratic; the singularity and 4ⁿ/(√π n^{3/2}).
- 13. Amortized analysis. The doubling array; a binary counter; aggregate, accounting and potential; growth factor 2 against 1.5 and an aggregate freed-size necessary condition, not guaranteed allocator reuse.
- 14. Sorting in practice. Timsort's comparisons on presorted data; the 2015 invariant bug; external merge sort and replacement selection (runs of 2,001 for M = 1,000).
- 15. The Job, sorted. The Job v1; counts on the corpus (15.0 billion key comparisons against 103 million); the instruction fit (maximum error under 0.5% on these ten held-out passages); grouped fitted terms, with rank 19/25 and nonunique attribution; explicitly enlarged arrays and 128 MiB modeled RAM; projected ledger row 7.
- 16. Frontier: beyond the worst case. a ten-trial Gaussian-noise illustration for one sorted input family; condition-specific historical integer-sorting results; fine-grained complexity; open problems. Outro.
What is computed and builtCost and measurement models
Quicksort and selection charge one logical three-way partition comparison per nonpivot key; this is not a count of Python predicates or CPU instructions. The distinct-key formulas use independent uniform pivots. Median-of-three and median-of-medians count their actual small-group insertion-sort tests. The median quickselect coefficient is asymptotic. The finite-group selection guarantee includes O(1) boundary terms; the elementary groups-of-three upper-bound recurrence does not establish a matching lower bound.
The recurrence pictures state their power-of-b/base conventions. The uneven numeric example uses T(n)=n for n≤2, then T(floor(n/3))+T(n-floor(n/3))+n. The doubling-array potential is max(0,2size−capacity), including the initial empty state. A freed-size sum does not model adjacency or fragmentation.
Native timings use positive clocks, minimum-of-three repeats and full sorted-reference checks outside timing.
The 32-bit methods share seeded inputs; counting uses the separately masked 16-bit domain. Input copies/reference
checks are excluded, while counting's counter allocation is included. Python sort comparisons are wrapper counts,
and its input labeled n/100 swaps performs exactly that many random transpositions. Library algorithms depend
on version: the measured Python uses powersort's merge policy; Rust replaced both standard sorts in 1.81.
The Job's corpus-sized static image is calibrated on 40 emulator passages and three core passages, with output
checks. Full-corpus native event counts are exact for that event model; fitted instructions, passage-IPC cycles
and seconds remain projections. The correlated fit has rank 19/25, so its grouped terms are not unique causal
instruction/time shares. Alternating scratch/source arrays is an optimization candidate requiring a changed
program and new measurement. The corrected v0 letter count is matched + same_length − (words − distinct):
matched letters plus the first mismatch on each unsuccessful same-length lookup.
比较模型先声明计什么:快速排序和选择对每个非枢轴键计一次逻辑划分比较,不是 Python 谓词或 CPU 指令数。 互异键期望式假设独立均匀枢轴;小组排序比较实际计数。递推注明基本情形与取整,空数组初始势能为零。 计时与比较次数分开,16 位计数排序与 32 位排序的值域分开,释放总大小与真实分配器复用分开。 语料事件、文本段实测、拟合指令数和 IPC 时间投影也分别注明。相关拟合系数不能直接当作因果时间份额。
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The ledger so far, and the question it raises: can thinking beat silicon?
- Models of computation: the RAM and the word-RAM (w ≥ log n); the pitfall of unit cost, repeated squaring timed in CPython (each step about three times the last); Turing machines, the comparison model, cell probes (Yao 1981), external memory (Aggarwal & Vitter 1988).
- Asymptotic notation, precisely (Bachmann 1894, Knuth 1976); the growth-rate ladder on log–log axes; the largest n per second, day and year at a nanosecond a step; Stirling's formula checked.
- Insertion sort: the loop invariant animated; inversions, n(n − 1)/4 derived and measured; binary insertion (fewer comparisons, the same moves).
- Merge sort: merging animated, stability; the recursion tree for T(n) = 2T(n/2) + n, drawn; the substitution method; comparisons against n lg n and ⌈lg n!⌉.
- The master theorem in its three cases, as level-by-level bars (Karatsuba, merge sort, a heavy combine); the geometric-series proof; five recurrences; Akra–Bazzi computed.
- The comparison lower bound: insertion sort's decision tree on three keys; log₂ n! = n log₂ n − n log₂ e + O(log n); each comparison gives at most one bit (callback to AI, Built 1); min-and-max by adversary, ⌈3n/2⌉ − 2 (Pohl 1972); Ford–Johnson merge insertion meets the bound for n ≤ 11 (verified exhaustively for n ≤ 8), and 30 > 29 at n = 12 (Wells 1965).
- Heapsort (Williams 1964); Floyd's heapify in O(n) (Σ h/2ʰ derived; under 2 comparisons per element measured); 1.8 n lg n measured; introsort.
- Quicksort (Hoare 1961): partition and Hoare's two pointers animated; expected comparisons 2(n + 1)Hₙ − 4n ≈ 1.39 n log₂ n, derived from the 2/(j − i + 1) argument and measured; first element, median of three and random pivots on sorted input (1,999,000 against about 21,000); dual pivot (Yaroslavskiy 2009).
- Concentration: the recurrence solved by telescoping; 10,000 runs at n = 1,000 (σ = 0.639 n against theory's √(7 − 2π²/3) n = 0.648 n); the tails; McDiarmid & Hayward 1996.
- Beating n log n: counting and radix sort, radix sort animated; timed in C (ten million keys: radix sort 3.8× faster
than
std::sort, 6.7× thanqsort); Hollerith; integer sorting on the word-RAM (Han & Thorup 2002, cited). - Selection: quickselect (3.36 n measured, (2 + 2 ln 2) n theory); median of medians (Blum, Floyd, Pratt, Rivest & Tarjan 1973), T(n) ≤ T(n/5) + T(7n/10) + O(n) solved, 8.29 n measured; why groups of five (three fails, seven works).
- Generating functions: Fibonacci and Binet, checked to n = 61; Catalan numbers from C = 1 + zC²; the singularity at 1/4 and 4ⁿ/(√π n^{3/2}), with the ratio computed (Flajolet & Sedgewick).
- Amortized analysis: the doubling array; a binary counter; aggregate, accounting and potential (Tarjan 1985); factor 2 against 1.5 on a million appends, and memory reuse below the golden ratio.
- Practice: Timsort's comparisons on presorted data; the 2015 run-stack bug found by KeY (de Gouw et al.); pdqsort; external merge sort and replacement selection (runs of 2,001 for M = 1,000).
- The Job v1 in the Pebble language, sort then count: 15.0 billion key comparisons against 103 million on the corpus; a 24-event instruction model (within 0.5% on held-out passages) applied through a C event counter; where the instructions go (half in comparison calls, a fifth in copying back); ledger row 7 (5.1 s, 11× row 5, 2.3× row 4). Frontier: smoothed analysis measured on quicksort (Spielman & Teng 2001); integer sorting results; fine-grained complexity (SETH, 3SUM, APSP; Backurs & Indyk 2015); open problems. Outro.
Computed: comparison counts for every sort on random, sorted and adversarial input, fitted to their formulas; the
quicksort histogram and tails; the decision-tree bound against Ford–Johnson for n ≤ 12; repeated squaring, radix
sort, std::sort and qsort timed on this machine; the Job v1 on the emulator, its instruction model, and the full
corpus counted by a C program.
Visuals: bars with the invariant region lit; merging and partitioning with pointers; recursion trees summing level
by level; a decision tree whose leaves are permutations; the growth ladder; radix passes; the histogram.
In practice: choosing standard-library sorts, complexity arguments in code review, the first questions of a coding interview.
Reading: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (CLRS) ch. 1–9, 16–17; Knuth, TAOCP 3 ch.
5; Sedgewick & Flajolet, An Introduction to the Analysis of Algorithms; Graham, Knuth & Patashnik, Concrete
Mathematics; Kleinberg & Tardos ch. 2, 5; Erickson, Algorithms; Flajolet & Sedgewick, Analytic Combinatorics;
Hoare 1962; Blum et al. 1973; de Gouw et al. 2015; Spielman & Teng 2001.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
插入排序的代价。 设 n ≥ 1,键互不相同。证明插入排序至多做 I + n − 1 次比较,其中 I 是逆序对的个数;并证明对互异键的均匀随机排列 E[I] = n(n − 1)/4。
解答
在元素 i 的内层循环里,每次比较要么找到一个更大的元素,把它右移一位,要么结束循环。一次右移交换一对相邻的 逆序元素,恰好消除一个逆序对且不产生新的,所以总共恰好 I 次右移,而每个 i 至多一次结束循环的比较:至多 I + n − 1 次比较。对随机顺序,n(n − 1)/2 对中的每一对由对称性以 1/2 的概率逆序(交换这一对的相对次序是各种顺序之间的双射), 由期望的线性性,E[I] = n(n − 1)/4。(
compute.py的insertion一项测量了这两者。) -
夹在两种情形之间。 设 n = 2^h,T(1) 为正常数,用递归树求解 T(n) = 4T(n/2) + n² lg n。
解答
第 j 层有 4ʲ 个规模为 n/2ʲ 的子问题,代价为 4ʲ (n/2ʲ)² lg(n/2ʲ) = n² (lg n − j)。对 j = 0, …, lg n 求和, 得 n² (lg n + (lg n − 1) + ⋯ + 0) = n² lg n (lg n + 1)/2 = Θ(n² log² n)。这是内部合并代价,还需加上 n² 个叶子的常数基本代价,不改变渐近结果。这里 f(n) = n^{log_b a} lg n 比 n^{log_b a} 大,但不是大一个多项式因子,所以基本定理的情形 2 和情形 3 都不适用;推广的情形 2(f = Θ(n^{log_b a} logᵏ n) 时 T = Θ(n^{log_b a} log^{k+1} n))给出相同的结果。
-
最小值与最大值。 设 n ≥ 1,元素互异。证明同时找出 n 个元素的最小值和最大值需要 ⌈3n/2⌉ − 2 次比较,并给出恰好用这么多次的算法。
解答
算法:先两两比较(⌊n/2⌋ 次),再在胜者中找最大、在败者中找最小(多出的一个元素两组都参加),各需 ⌈n/2⌉ − 1 次:共 ⌈3n/2⌉ − 2 次。下界:如果一个元素在某次比较中较大,就说它“赢过”,较小则“输过”。结束时,除最大值外 每个元素都必须输过,除最小值外每个元素都必须赢过:共 2n − 2 个信息单位。两个从未比较过的元素之间的比较给出两个单位; 对其他每次比较,对手总能回答得只给出至多一个单位(把赢过的当作大、输过的当作小,回答总能保持一致)。两个从未比较过的 元素之间的比较至多 ⌊n/2⌋ 次,所以比较次数至少为 ⌊n/2⌋ + (2n − 2 − 2⌊n/2⌋) = ⌈3n/2⌉ − 2(波尔,1972)。
-
用快速选择找最小值。 假设键互异、枢轴独立均匀,每轮对每个非枢轴键计一次逻辑比较。证明快速选择在找最小值时平均做 2n − 2Hₙ 次比较。
解答
n − 1 次比较之后,枢轴的秩 r 是均匀的;r = 1 时结束,否则在比它小的 r − 1 个元素上递归。所以 Cₙ = n − 1 + (1/n) Σ_{k=0}^{n−1} C_k。乘以 n,再减去 n − 1 时的同一个方程,得 nCₙ − (n − 1)C_{n−1} = 2(n − 1) + C_{n−1},即 Cₙ = C_{n−1} + 2 − 2/n。由 C₁ = 0 求和得 Cₙ = 2n − 2Hₙ:大约是直接扫描一遍的 n − 1 次的两倍。
-
动手:给任务用基数排序。 用 Pebble 语言把任务 v1 改写成按字母做基数排序,并在我们的文本段上与归并排序比较 指令数。
解答
解答要点。 用最高位优先的基数排序,每层 27 个桶(词尾,然后 a 到 z):数出每个桶里的出现次数,算出偏移量,稳定地 分发到一个临时数组,再对每个桶按下一个字母递归,桶小于大约 16 个元素时改用插入排序。分发每层只对所处理的前缀字母读取常数次,需要时还包括词尾桶;重复单词必须一直处理到词尾。这用前缀工作替代重复的整键比较,但精确工作量仍需在实现中计数;但每一层递归都要为它的 27 个计数器付出代价,这在小文本段上占主导。用
FEATURES_C的 一个变体在语料上计算区分前缀总长度,像job.py那样拟合新程序的指令数,再作比较:归并排序与基数排序的交叉点就是 答案。 -
★ 研究:固定模型的整数排序。 先固定允许指令、随 n 变化的字宽、空间预算和随机性保证。找出所引线性时间结果中的一个限制,提出精确扩展或下界目标。有限 32 位基数排序对比实验是另一个可复现构建任务,不能解决所有增长字宽下的定理问题。
从哪里开始。 上界:弗雷德曼与威拉德的融合树(1990)首先突破了 n log n;安德松、哈格鲁普、尼尔松与拉曼(1995) 在 O(n log log n) 内排序,当字长至少为 log^{2+ε} n 时可达随机化期望线性时间;韩与托鲁普(2002)达到期望 O(n √(log log n)); 贝拉祖吉、布罗达尔与尼尔森(2014)对 Ω(log² n log log n) 位的字给出期望线性时间。下界:字 RAM 上的排序还没有已知的 超线性下界;在受限模型(比较模型、AC⁰ 指令集)以及前驱查找等相关问题上有强下界(珀特拉什库与托鲁普,2006)。 这些是历史起点:核对了选定作者和大学页面的摘要,没有审计全部证明或所有最新结果。先核对指令与随机性条件,再说明所提扩展能改进什么;有限 32 位测量必须与跨字宽定理分开。
Build the film
python -m videos.cs.cs16.compute # the part's numbers, into .cache/cs16
python tools/build.py cs16 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs16 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs16. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs16.compute # every number in the part (a few minutes)
python tools/build.py cs16 -q l # a 480p preview
python tools/build.py cs16 # 1080p