|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/sort realize the sorts of the book, i.e., the elementary ones of section 2.7, Quicksort of section 12.2, heapsort of section 10.1.4 and Shell Sort of section 15.1, and many beyond it, from the internal sorts of Knuth to the quicksorts, the merge sorts and the radix sorts engineered for the memory and for the vector registers of today, of which sort() and stableSort() of Sort.h choose one for each input (pdqSort() and powerSort() are their engines for the items that no faster route takes, kept also where Boost is found, whose boost::sort::pdqsort and spinsort a program may call directly). This page collects what the headers take for granted: the definitions and the notation shared by all of them (see Definitions and notation), the lower bound that the sorts by comparisons cannot beat (see The lower bound of the sorts by comparisons), and, for each family of algorithms, the property on which its correctness rests and the argument behind its bound (from The elementary sorts and the inversions to Networks, other measures and external memory), with a table that compares them all (see The sorts compared). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.
A sort rearranges a vector \( A[ 0 .. n - 1 ] \) of items so that \( A[ i - 1 ] \le A[ i ] \) for each \( 0 < i < n \), where \( \le \) is a total preorder given by the comparator less of the call (the relation \( a < b \) being less( a , b )); two items are equal when neither is smaller than the other, which need not make them the same item. A sort is stable (section 12.5 of the book) if the equal items keep the order that they had, which matters when the items are records sorted by one of their fields, and it is in place if it uses \( O( 1 ) \) extra items, or \( O( \log n ) \) extra words for a stack. A sort by comparisons learns about the items only through less, and works therefore with any order; the sorts by digits (counting, pigeonhole, radix) read the keys as integers or strings instead, and are not bound by the lower bound of the sorts by comparisons (see The lower bound of the sorts by comparisons).
| Symbol | Meaning |
|---|---|
| \( n \), \( A[ 0 .. n - 1 ] \) | the number of items and the vector that holds them, with \( A[ \mathit{lo} .. \mathit{hi} - 1 ] \) a part of it |
| \( I( A ) \) | the inversions of \( A \), the pairs \( i < j \) with \( A[ j ] < A[ i ] \); \( 0 \le I( A ) \le n ( n - 1 ) / 2 \), and \( n ( n - 1 ) / 4 \) on average over the permutations (countInversions()) |
| \( r \), \( \ell_1 , \ldots , \ell_r \) | the runs of \( A \), its maximal non-decreasing (or strictly decreasing) stretches, and their lengths |
| \( H \) | the entropy \( \sum_i ( \ell_i / n ) \log_2( n / \ell_i ) \) of the lengths of the runs, between 0 (one run) and \( \log_2 n \) (\( n \) runs of one item) |
| \( k \) | the number of distinct keys, or the range \( [ 0 , k ) \) of integer keys |
| \( w \) | the bytes (or bits) of a key read by a radix sort |
| \( D \) | the total length of the distinguishing prefixes of a set of strings, the shortest prefix of each string that tells it from all the others |
| \( \sigma \) | the size of the alphabet of the strings, 256 for the bytes |
| \( W \) | the lanes of a vector register, 4 to 16 keys |
Each sort ends, at the level of the audits [see Contract.h], with the check of sortedPermutation() of Sorted.h: the output is sorted and holds the items of the input, which a copy sorted by std::sort and compared item by item through the equivalence of less tells in \( O( n \log n ) \).
Theorem 1 (the decision tree, section 2.7.4 of the book). Any sort by comparisons makes, on some input of \( n \) distinct items, at least
\[ \lceil \log_2 n! \rceil \ge n \log_2 n - n \log_2 e \approx n \log_2 n - 1.443 \, n \tag{1} \]
comparisons, and as many, but for a term \( O( n ) \), on average over the permutations of the input.
Indeed, the comparisons that a sort makes form a binary tree, each node a comparison and each leaf an output; the \( n! \) orders of distinct items need \( n! \) different outputs, and a binary tree with \( n! \) leaves has height at least \( \log_2 n! \) and average depth of a leaf at least \( \log_2 n! \) too. The inequality of (1) follows from \( n! \ge ( n / e )^n \). Hence merge sort and heapsort, with \( O( n \log n ) \) comparisons in the worst case, and Quicksort on average, are optimal up to a constant factor; the merge insertion of Ford and Johnson (mergeInsertionSort() of KnuthSorts.h) exceeds \( \log_2 n! \) by between about \( 0.028 \, n \) and \( 0.114 \, n \) comparisons in the worst case, and for \( n \le 11 \) and \( n = 20 , 21 \) it meets (1).
The same argument gives finer bounds when the input is restricted. If the input is known to consist of \( r \) runs of lengths \( \ell_1 , \ldots , \ell_r \), the possible outputs are the ways of interleaving them, \( n! / ( \ell_1! \cdots \ell_r! ) \), and the bound becomes
\[ \log_2 \frac{n!}{\ell_1! \cdots \ell_r!} \ge n H - O( n ) , \tag{2} \]
which is 0 on a sorted input and (1) on \( n \) runs of one item; the merge sorts of RunSorts.h meet (2) up to \( O( n ) \) (see Merge sorts and runs). Likewise, with \( k \) distinct keys, each repeated \( n / k \) times, the bound is \( n \log_2 k - O( n ) \), which the partitions by three ways meet (see Quicksort and its variants). The sorts by digits escape (1), since a single step of theirs, the address \( B[ \mathit{key} ] \) of an array of counts, has \( k \) outcomes instead of 2; they are linear when the keys are short (see Sorts by digits).
The elementary sorts of section 2.7 keep a sorted prefix \( A[ 0 .. i - 1 ] \) and extend it by one item at each step. Selection Sort (selectionSort() of SelectionSort.h) appends the minimum of the rest, whatever the input, with \( n ( n - 1 ) / 2 \) comparisons and at most \( n - 1 \) swaps. Insertion Sort (insertionSort() of InsertionSort.h) inserts \( A[ i ] \) in the prefix, moving right the items larger than it, and its cost depends on the input as follows.
Lemma 2 (the inversions). Insertion Sort makes exactly \( I( A ) \) moves and at most \( I( A ) + n - 1 \) comparisons; any sort that only swaps adjacent items makes at least \( I( A ) \) swaps, and hence
\[ \frac{n ( n - 1 )}{4} \tag{3} \]
on average over the permutations.
In fact, the item \( A[ i ] \) moves past exactly the items of the prefix larger than it, i.e., the inversions \( ( j , i ) \) with \( j < i \), and each test of the inner loop but the last one is followed by a move. A swap of two adjacent items changes \( I( A ) \) by exactly one, and a permutation and its reverse together have \( n ( n - 1 ) / 2 \) inversions, which gives (3). Insertion Sort is thus \( \Theta( n ) \) on an input with \( O( n ) \) inversions, and with its simple loop it is the fastest on a few items, which makes it the base case of all the hybrid sorts of the area. The sorts by adjacent exchanges of ExchangeSorts.h (bubble, cocktail shaker, odd-even transposition, gnome) and the binary and list insertion sorts of KnuthSorts.h are all bound by (3) in their moves or swaps.
Shell Sort (shellSort() of ShellSort.h, section 15.1) escapes (3) by exchanging far items first: a pass with gap \( h \) is an insertion sort of the \( h \) interleaved subsequences, and a swap at distance \( h \) may remove up to \( 2 h - 1 \) inversions. A vector that is \( h \)-sorted stays \( h \)-sorted after a pass with a smaller gap, which is why the last pass, with gap 1, finds few inversions. The time depends on the gaps, which the header compares: \( \Theta( n^2 ) \) in the worst case with the gaps \( n / 2^j \) of Shell, whose common factors leave the odd and the even places apart until the last pass; \( O( n^{3/2} ) \) with \( 2^j - 1 \) (Hibbard) and with \( ( 3^j - 1 ) / 2 \) (the book); \( O( n \log^2 n ) \) with all the \( 2^i 3^j \) (Pratt), since a vector that is 2-sorted and 3-sorted needs a single pass of adjacent swaps to be 1-sorted.
Merge Sort (mergeSort() of MergeSort.h, section 2.7.3) splits the vector into two halves, sorts them recursively and merges them; the merge of two sorted vectors of \( n_1 \) and \( n_2 \) items takes at most \( n_1 + n_2 - 1 \) comparisons, since each comparison outputs an item, and it is stable if the left item goes first on a tie. Hence, in the worst case,
\[ T( n ) = T( \lceil n / 2 \rceil ) + T( \lfloor n / 2 \rfloor ) + n - 1 = n \lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1 , \tag{4} \]
within \( n \) comparisons of (1), at the price of a buffer of \( n \) items. The bottom-up version (mergeSortBottomUp()) merges the runs of lengths \( 1 , 2 , 4 , \ldots \) with no recursion, and a merge also counts the inversions, since an item taken from the right half overtakes all the items left in the left one (countInversions()).
The natural merge sorts merge the runs that the input already has instead of the halves, and the order of the merges decides the cost: merging two runs costs their total length, so that a sequence of merges is a binary tree over the runs whose cost is the sum of \( \ell_i \cdot \mathrm{depth}( i ) \), as in the codes of Huffman, and the best tree costs between \( n H \) and \( n H + n \). Timsort keeps the runs on a stack whose lengths grow from the top at least as the Fibonacci numbers, merging when the rule fails; the stack has thus \( O( \log n ) \) runs, and its merges cost \( O( n + n H ) \) comparisons (Auger, Jugé, Nicaud and Pivoteau). Powersort (powerSort() of RunSorts.h) merges along a tree that is nearly the one of the midpoints: the boundary between two adjacent runs has the power of the first bit where their midpoints, as fractions of \( n \), differ, and a run on the stack is merged when its boundary has a larger power than the new one; this tree costs at most \( n H + 2 n \) (Munro and Wild), within \( O( n ) \) of (2). It extends the runs shorter than \( \mathit{minrun} \) (24 items) by binary insertion, and gallops (an exponential search, then a binary one) when one run keeps winning, so that two runs one after the other merge in \( O( \log n ) \) comparisons. The strand sort of StrandSort.h builds runs of its own, the strands being as many as the items of a longest strictly decreasing subsequence.
Quicksort (quickSort() of QuickSort.h, section 12.2) partitions the part around a pivot \( x \), the smaller items before it and the others after it, and sorts the two sides recursively; the partition costs \( n - 1 \) comparisons, and the sides may be anything from 0 to \( n - 1 \) items.
Theorem 3 (Quicksort on average). With the pivot of a part equally likely to be any of its items, e.g., on a random permutation or with a pivot chosen at random, the expected number of comparisons \( C( n ) \) satisfies
\[ C( n ) = n - 1 + \frac{2}{n} \sum_{j=0}^{n-1} C( j ) = 2 ( n + 1 ) H_n - 4 n \approx 1.386 \, n \log_2 n , \tag{5} \]
\( H_n = \sum_{i=1}^{n} 1 / i \) the harmonic numbers.
Indeed, the pivot is the \( j + 1 \)-th smallest with probability \( 1 / n \), and leaves sides of \( j \) and \( n - 1 - j \) items, which are again random; this gives the recurrence. Subtracting the one of \( n - 1 \) multiplied by \( n - 1 \) from the one of \( n \) multiplied by \( n \) gives \( n C( n ) = ( n + 1 ) C( n - 1 ) + 2 ( n - 1 ) \), and dividing by \( n ( n + 1 ) \) telescopes to (5). Equivalently, the items of ranks \( i < j \) are compared if and only if one of them is the first pivot among the ranks \( i , \ldots , j \), which happens with probability \( 2 / ( j - i + 1 ) \), and the sum of these probabilities is (5). In the worst case, a pivot that is always the smallest item (the first item of a sorted vector) gives \( n ( n - 1 ) / 2 \) comparisons and \( n - 1 \) levels of recursion.
The variants of the area act on the three weak points of (5): the constant, the worst case and the equal keys. The pivot as the median of three, or of three medians of three (the ninther of Tukey), lowers the constant of (5) to about \( 1.188 \) and makes the sorted inputs a good case (quickSortTuned(), pdqSort()). The introsort of Musser bounds the depth of the recursion by \( 2 \lfloor \log_2 n \rfloor \) and sorts a part that goes deeper by heapsort (vectorQuickSort()); pdqSort() allows instead \( \lfloor \log_2 n \rfloor + 1 \) partitions with a side below \( n / 8 \), and the worst case is \( O( n \log n ) \) in both; recurring on the smaller side and looping on the larger keeps the stack within \( \log_2 n \) parts, since each recursive call at least halves the part. A partition by three ways keeps the items equal to the pivot apart (threeWayQuickSort(), Algorithm 5.4 of chapter 5, Sorting Atomic Items, of Ferragina's book, with a random pivot), or skips a run of them when the pivot equals the item before the part (pdqSort() of Peters), so that the keys equal to a pivot are never examined again, and \( k \) distinct keys cost \( O( n \log k ) \), the lower bound for them (see The lower bound of the sorts by comparisons). Two pivots split the part into three in one pass (dualPivotQuickSort() of Yaroslavskiy, section 5.3.5 of the same chapter), with about \( 1.9 \, n \ln n \) comparisons against the \( 2 \, n \ln n \) of (5) but fewer scans of the memory (Wild and Nebel). Finally, the speed of a partition on a modern processor depends less on its comparisons than on the branches that it mispredicts: the BlockQuicksort of Edelkamp and Weiss (inside pdqSort()) and vectorQuickSort() of VectorQuickSort.h, which compares \( W \) keys with the pivot in one instruction and writes them with a compressed store, make the partition free of branches on the keys.
Samplesort (sampleSort() of SampleSort.h) generalizes the pivot to \( k - 1 \) splitters drawn from a sample of \( \alpha k - 1 \) items, and distributes the items into \( k \) buckets by a search in a tree of the splitters with no branch (Sanders and Winkel), in place by blocks (Axtmann, Witt, Ferizovic and Sanders). With \( k = 256 \) there are about \( \log_{256}( n / 16 ) \) levels of distribution, each reading and writing every item twice; the expected comparisons are \( n \log_2 n + O( n ) \), since each level compares an item with \( \log_2 k \) splitters, and the sample makes a bucket much larger than \( n / k \) unlikely.
The learned sort (learnedSort() of LearnedSort.h, after Kristo et al. and Ferragina and Odorisio) keeps the splitters of samplesort but replaces the search among them by a model of the cumulative distribution function \( F \) of the keys, \( F( x ) \) the fraction of the keys not larger than \( x \). A distribution into \( k \) buckets is balanced when the bucket of \( x \) is \( \lfloor k F( x ) \rfloor \), and the splitters at the quantiles \( i / k \) of a sample approximate it within the error of the empirical CDF \( F_s \) of the sample, which is bounded whatever \( F \) is.
Lemma 4 (Dvoretzky, Kiefer and Wolfowitz, with the constant of Massart). For a sample of \( s \) keys drawn independently from \( F \), and every \( \varepsilon > 0 \),
\[ \Pr\Bigl[ \sup_x | F_s( x ) - F( x ) | > \varepsilon \Bigr] \le 2 e^{-2 s \varepsilon^2} . \tag{6} \]
The proof is in the paper of Massart. With \( s = 16 k \) places of the sample independent and uniform (an assumption of the model, since the places come from a xorshift seeded by \( n \)) and \( \varepsilon = c / \sqrt{s} \), (6) gives every bucket between two consecutive distinct splitters at most \( n / k + 2 \varepsilon n \) keys with probability at least \( 1 - 2 e^{-2 c^2} \), a constant rather than a high probability; the keys equal to a splitter have a bucket of their own when the sample repeats a splitter, and otherwise join the bucket below it, which may then hold up to \( 2 n / k + 2 \varepsilon n \) keys. The model evaluates the number of splitters less than \( x \) by a grid of cells of equal width \( w \), a power of 2, on the range of the sample: the cell of \( x \) is a shift of \( x - S_{\min} \), each cell keeps the number of splitters before it (a histogram of the sample and its prefix sums), and if no cell holds more than \( c_{\max} \) splitters the bucket is that count plus \( c_{\max} \) comparisons with no branch, in \( O( 1 ) \) time instead of the \( \log_2 k \) dependent loads of a search. The grid fails exactly where the keys are dense with respect to their mean on the range (the laws with a heavy tail, the clusters far apart) or the sample repeats its quantiles (few distinct keys); both are seen on the sample before any key moves, and the sort then falls back to samplesort. When the model fits, the classification and the moves cost \( O( n ) \) and the sorts of the buckets \( O( n \log( n / k ) ) \) in expectation.
A max-heap on a vector has \( A[ \lfloor ( i - 1 ) / 2 \rfloor ] \ge A[ i ] \) for each \( i > 0 \), and its maximum in \( A[ 0 ] \) (section 10.1.4). maxHeapRestore() of Heapsort.h moves an item down from a node of height \( m \) in \( O( m ) \), and heapBuild() calls it on the internal nodes from the last one up; since at most \( \lceil n / 2^{m+1} \rceil \) nodes have height \( m \), the build costs
\[ \sum_{m \ge 0} \Bigl\lceil \frac{n}{2^{m+1}} \Bigr\rceil O( m ) = O\Bigl( n \sum_{m \ge 0} \frac{m}{2^m} \Bigr) = O( n ) , \tag{7} \]
the series being 2. Heapsort then swaps the maximum with the last place of the heap and restores it \( n - 1 \) times, \( O( n \log n ) \) in all and in place, with about \( 2 n \log_2 n \) comparisons; it is the fallback of the introsorts because its bound holds on every input. The tournament sort of KnuthSorts.h plays a knockout on a complete tree of the items and replays only the path of the winner, \( \lceil \log_2 n \rceil \) comparisons for each item, and the tree sort of TreeSort.h inserts the items in a search tree and reads them back in symmetric order, \( O( n \log n ) \) on a balanced tree and \( \Theta( n^2 ) \) on a sorted input with no balance.
Counting Sort (countingSort() of CountingSort.h, section 2.7.5) counts the occurrences of each integer key in \( [ 0 , k ) \) and writes them back in order, in \( \Theta( n + k ) \) time; Pigeonhole Sort (pigeonholeSort() of PigeonholeSort.h, exercise 4.11) appends each item to the list of its key and concatenates the lists, which carries the values along and is stable. A radix sort applies a stable distribution to each digit of the keys, and its correctness rests on the following.
Lemma 5 (the least significant digit first). If the keys have \( w \) digits, and each pass distributes the items stably by one digit, from the least significant to the most, then after the pass on the digit \( j \) the items are sorted by the number formed by their digits \( 0 , \ldots , j \).
Indeed, after the pass on \( j \) two items with different digits \( j \) are in the order of those digits, and two with the same digit \( j \) keep the order that they had, i.e., by induction, the order of their digits \( 0 , \ldots , j - 1 \). Hence radixSort() of RadixSort.h, with bytes as digits, takes \( O( w ( n + 256 ) ) \), linear for keys of a fixed width, and skips the bytes in which no two keys differ; its keys make the order of the numbers that of unsigned integers (the sign bit flipped, and all the bits of a negative floating point number). The sorts from the most significant digit (americanFlagSort(), msdRadixSort()) distribute by the first digit and recur on each bucket, reading only the digits that tell the keys apart; on strings they read \( D \) characters, which any sort of strings must read, and spend \( O( n \log \sigma ) \) beyond them on an alphabet of \( \sigma \) characters. americanFlagSort() permutes the items in place, not along the cycles of the permutation, whose every step waits for the load of the one before, but by rounds in which each item of a bucket is swapped to the next free place of its own, so that the loads of a round are independent, and leaves the buckets of fewer than kFlagSmall items to a quicksort, whose partitions in the vector registers cost less than the passes by a byte that they replace. The multikey quicksort of Bentley and Sedgewick (multikeyQuickSort(), of chapter 7, Sorting Strings, of Ferragina's book) partitions by three ways on one character at a time, \( O( D + n \log n ) \) comparisons of characters, and prefixKeySort() of StringSort.h turns 8 characters at a time into integer keys sorted in the vector registers.
A sorting network (SortingNetworks.h) is a fixed sequence of comparators \( ( i , j ) \), each putting the smaller of \( A[ i ] \) and \( A[ j ] \) in \( A[ i ] \), whatever the input; the comparators of a round touch disjoint places and run in parallel. Its correctness rests on the 0-1 principle of Knuth: a network sorts every input if and only if it sorts the \( 2^n \) inputs of zeros and ones, since a comparator commutes with every non-decreasing function of the items, and an input out of order at the end gives, through a threshold, an input of zeros and ones out of order. The bitonic sorter and the merge exchange of Batcher take \( O( \log^2 n ) \) rounds and \( O( n \log^2 n ) \) comparators, more than (1), which they pay for with their parallelism; the network of vectorQuickSort() sorts \( 16 W \) keys in the registers in this way.
A file larger than the memory is sorted in two phases (ExternalSort.h, sections 5.4.1 and 5.4.2 of Knuth). The replacement selection keeps \( M \) items in a heap and outputs the least that can extend the current run; on random input the runs are about \( 2 M \) long, twice the \( M \) of sorting one memory load at a time (the snowplow argument of Knuth). The polyphase merge deals the runs on \( T - 1 \) tapes in a generalized Fibonacci distribution, padded with empty runs, so that each phase merges until one tape is empty and that tape becomes the next output; with three tapes each item takes part in about \( \log_\phi r \) merges, \( \phi \) the golden ratio, and no tape is ever only copied.
| Sort | Worst case | Average case | Extra space | Stable |
|---|---|---|---|---|
| selectionSort() | \( \Theta( n^2 ) \) | \( \Theta( n^2 ) \) | \( O( 1 ) \) | no |
| insertionSort() | \( \Theta( n^2 ) \) | \( \Theta( n + I( A ) ) \) | \( O( 1 ) \) | yes |
| shellSort() | \( O( n^{3/2} ) \) (book's gaps) | depends on the gaps | \( O( 1 ) \) | no |
| mergeSort() | \( \Theta( n \log n ) \) | \( \Theta( n \log n ) \) | \( \Theta( n ) \) | yes |
| powerSort() | \( O( n + n H ) \) | \( O( n + n H ) \) | \( O( n ) \) | yes |
| quickSort() | \( \Theta( n^2 ) \) | \( 1.386 \, n \log_2 n \) | \( O( n ) \) stack | no |
| pdqSort(), vectorQuickSort() | \( O( n \log n ) \) | \( O( n \log n ) \), \( O( n \log k ) \) for \( k \) keys (pdqSort(), vectorQuickSort()) | \( O( \log n ) \) stack | no |
| sampleSort() | \( O( n \log n ) \) | \( n \log_2 n + O( n ) \) | \( O( k b ) \) items, blocks of \( b \) | no |
| learnedSort() | \( O( n \log n ) \), by sampleSort() when the model does not fit | \( O( n \log( n / k ) ) \) when it fits | \( \Theta( n ) \) | no |
| heapsort() | \( O( n \log n ) \) | \( O( n \log n ) \) | \( O( 1 ) \) | no |
| countingSort() | \( \Theta( n + k ) \) | \( \Theta( n + k ) \) | \( \Theta( k ) \) | not applicable |
| radixSort() | \( O( w ( n + 256 ) ) \) | \( O( w ( n + 256 ) ) \) | \( \Theta( n ) \) | yes |
| msdRadixSort() | \( O( D + n \log \sigma ) \) | \( O( D + n \log \sigma ) \) | \( \Theta( n ) \) | not applicable |
The bounds of the table are in comparisons for the sorts by comparisons and in time for the others; the stability is not applicable where equal items cannot be told apart (integers, strings).
The sorts of chapter 11 of Morin's book are those of this area: its merge sort is mergeSort(), its quicksort, with the random pivot and the partition in three, threeWayQuickSort() (EngineeredQuickSorts.h), its heap sort heapsort(), on a heap of the maximum instead of the minimum, which spares the final reversal of the book (exercise 11.9 of the Java edition: the comparator negated would cost a negation per comparison, \( \Theta( n \log n ) \), against the \( n / 2 \) swaps of the reversal), its counting sort and radix sort countingSort() and radixSort(), the latter on signed integers too, the sign bit flipped in the key (exercise 11.13), and the merge sort of a list without an array listSort() (ListSort.h), which relinks the cells (exercise 11.2).
Lemma 6 (the adversary of quicksort). For any quicksort that takes its pivot among \( O( 1 ) \) items of its part, deterministically or at random, the comparator of McIlroy (QuicksortAdversary.h) makes it do at least \( \binom{n}{2} \) comparisons on \( n \) items, and the values it gives are an input on which a deterministic such sort does the same comparisons (exercises 11.3 to 11.6).
Indeed, the adversary freezes the candidate for the pivot, the gas item last compared with a frozen one, at the first comparison of a partition between two gas items, to the smallest value still free: the pivot is then below all the gas of its part, the partition sends all of it to one side, and a part of \( k \) items costs \( k - 1 \) comparisons or more, the next part having \( k - 1 \) items. Its answers are those of the total order of the values given, the gas after the frozen ones, so that the same sort, replayed on those values, gets the same answers. The sorted array is the killer input of the first item as the pivot, and the input that the adversary leaves for the middle item is one for that rule; for any rule that does not look at the values the adversary builds one (exercise 11.5).
Lemma 7 (the expected comparisons of the quicksort of the book). The quicksort of Morin's book, which compares the \( k \) items of a part with its pivot, the pivot itself included, and returns at once on the parts of at most one item, makes on \( n \ge 2 \) distinct keys
\[ T( n ) = 2 ( n + 1 ) H_n - 4 n + \frac{2 n - 1}{3} \tag{8} \]
comparisons in expectation, \( H_n \) the harmonic number.
Indeed, \( T( n ) = n + ( 2 / n ) \sum_{k<n} T( k ) \) with \( T( 0 ) = T( 1 ) = 0 \), which is the recurrence of the classical count, \( 2 ( n + 1 ) H_n - 4 n \) for \( n - 1 \) comparisons per part, plus one comparison per part of at least two items; the parts are one per pivot, \( n \) in all, of which the parts of one item are \( ( n + 1 ) / 3 \) in expectation for \( n \ge 2 \), hence the \( n - ( n + 1 ) / 3 \) of (8). The \( 2 n H_n - n + H_n \) that exercise 11.7 states is not the expectation of that count, nor of the count without the pivot, \( 2 ( n + 1 ) H_n - 4 n \): it differs from (8) already at \( n = 2 \), where both counts are exact (2 and 1) and the formula gives 5.5; the test ods.ex11.7.quicksort-expectation checks (8) on the recurrence up to 2000 and on the average of the quicksort of the book.
The heap sort of the book, on an array in increasing order, already a heap of the minimum, does at least \( 2 n \log_2 n - O( n ) \) comparisons: the leaf moved to the root at each step, one of the largest items left, sinks back to the bottom, with two comparisons per level, the count that the test ods.ex11.8.heapsort-worst checks against \( 2 n \log_2 n - 4 n \) (exercise 11.8). The comparison tree of figure 11.6 has 4 leaves for the 6 permutations of three items, and besides \( 3 , 1 , 2 \) and \( 3 , 2 , 1 \), which the book shows, the pair \( 2 , 3 , 1 \) and \( 3 , 1 , 2 \) reaches the same rightmost leaf, which orders \( 2 , 3 , 1 \) wrongly (exercise 11.9). A binary tree of \( k \) leaves has height at least \( \log_2 k \), since a tree of height \( h \) has at most \( 2^h \) leaves (exercise 11.11), and a leaf drawn at random has expected depth at least \( \log_2 k \), by induction with \( ( k_1 / k ) \log_2 k_1 + ( k_2 / k ) \log_2 k_2 \ge \log_2 k - 1 \) for \( k_1 + k_2 = k \), the convexity of \( x \log x \) (exercise 11.12); hence \( \log_2 n! = n \log_2 n - O( n ) \) comparisons, by the formula of Stirling, \( \log_2 n! = n \log_2 n - n \log_2 e + O( \log n ) \) (exercise 11.10), even in expectation over the random choices of a sort. Exercise 11.1 is the trace of the sorts on \( 1 , 7 , 4 , 6 , 2 , 8 , 3 , 5 \), in the test ods11.1.sorts.