Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Comparison sorting: quicksort, heapsort and Shell’s method

ProblemPut the elements of a slice in order, using only comparisons between them, in place
Devised byTony Hoare (1961), quicksort; David Musser (1997), introsort; J. W. J. Williams (1964) and Robert Floyd (1964), heapsort; Donald Shell (1959), diminishing-increment sort; Marcin Ciura (2001), gap sequence
AccuracyExact; every result is checked against the standard library’s sort in the generator
CostQuicksort on average, about comparisons, and worst case with the heapsort fallback; heapsort worst case, about comparisons; Shell’s method about empirically
Read firstNothing beyond the Preliminaries
APIquicksort, heapsort, shell_sort

Overview

Sorting is the most studied problem in computing: it makes searching, merging, deduplication, ranking and grouping cheap, and many algorithms begin by sorting their input. A comparison sort learns about the order only by comparing pairs of elements. Any such sort needs at least comparisons in the worst case, because each comparison can at best halve the possible orders. The three sorts here all work in place, using only or extra memory, and none is stable: equal elements may change their relative order. Each takes any T: Ord.

  • Quicksort splits the slice around a pivot and recurses. It is the fastest on average.
  • Heapsort builds a binary heap and repeatedly removes its largest element. It guarantees .
  • Shell’s method is insertion sort over shrinking gaps. It is short and adapts to nearly sorted data.

Where it is used

Sorting is probably the most common operation in computing.

  • Databases and search. Ordered data can be searched by binary search and merged efficiently.
  • Graphics and geometry. Sorting points or objects by depth or coordinate is a first step in rendering, hulls and sweep-line algorithms.
  • Statistics. Medians, quantiles and ranks need sorted data.
  • Practical choice. Quicksort is fast on average, heapsort has a guaranteed bound and Shell’s sort is simple and good for small arrays.

History

Tony Hoare invented quicksort in 1959 while working on machine translation in Moscow, and published it in 1961. Robert Sedgewick’s 1975 thesis analysed it in depth and introduced the median-of-three pivot, with Bentley and McIlroy (1993) and Musser’s introsort (1997) adding defences against bad inputs. J. W. J. Williams introduced the binary heap and heapsort in 1964, and Robert Floyd improved its construction the same year to linear time. Donald Shell published his method in 1959. Its cost depends on the gap sequence and is still not fully understood. Marcin Ciura found the empirically best short sequence (1, 4, 10, 23, 57, 132, 301, 701) by computer search in 2001.

The idea

Quicksort

Choose a pivot, rearrange the slice so that smaller keys come before it and larger ones after (partitioning), and sort the two sides recursively. A balanced split gives ; a pivot that is always the smallest or largest key gives . The library’s version follows Sedgewick’s recommendations:

  • the pivot is the median of three: the first, middle and last keys;
  • Hoare’s partition scans inwards from both ends, swapping pairs that are on the wrong sides;
  • ranges of 16 or fewer keys are finished by insertion sort, which is faster on small inputs;
  • recursion goes into the smaller side and loops on the larger, so the stack depth is at most ;
  • after partitions, a range still unsorted is finished by heapsort (introsort).

Both of Hoare’s scans stop at keys equal to the pivot. That seems wasteful, but it splits a run of equal keys evenly between the sides. A partition that sends all equal keys to one side takes on input with few distinct values. Such a partition took 0.7 s on 40 000 equal keys. A three-way partition cures that but rearranges sorted input badly (a million sorted keys took 4 s), so the library uses Hoare’s partition.

/// Hoare's partition around a median-of-three pivot; returns the pivot's final index, with
/// smaller-or-equal keys before it and greater-or-equal keys after.
fn partition<T: Ord>(s: &mut [T]) -> usize {
    let last = s.len() - 1;
    let mid = last / 2;
    if s[mid] < s[0] {
        s.swap(mid, 0);
    }
    if s[last] < s[0] {
        s.swap(last, 0);
    }
    if s[last] < s[mid] {
        s.swap(last, mid);
    }
    // Now s[0] <= s[mid] <= s[last]. The median becomes the pivot at index 0, where it stops the
    // right-to-left scan, and s[last] >= pivot stops the left-to-right one.
    s.swap(0, mid);
    let (mut i, mut j) = (0, s.len());
    loop {
        i += 1;
        while s[i] < s[0] {
            i += 1;
        }
        j -= 1;
        while s[0] < s[j] {
            j -= 1;
        }
        if i >= j {
            break;
        }
        s.swap(i, j);
    }
    s.swap(0, j);
    j
}

Median-of-three makes sorted, reversed and organ-pipe inputs fast, but an adversary can still build inputs that make every pivot bad (Musser’s “median-of-3 killer” sequences). Douglas McIlroy’s “killer adversary” (1999) finds such an input for any quicksort. It treats every key as undecided “gas” until the sort compares two of them, then fixes values so that the current pivot is as bad as possible. Against the library’s quicksort it forced about comparisons: 16 million for 8000 keys.

Introsort (Musser, 1997) bounds the damage. Balanced partitions finish in about levels, so a range still unsorted after partitions is a sign of bad pivots, and it is handed to heapsort. Typical inputs never reach the limit and run as plain quicksort. The fallback holds an adversary to comparisons. Rust’s standard sort_unstable (pattern-defeating quicksort) uses the same safeguard.

fn introsort<T: Ord>(slice: &mut [T], mut depth: usize) {
    let mut slice = slice;
    loop {
        if slice.len() <= 16 {
            insertion_sort(slice);
            return;
        }
        if depth == 0 {
            // Too many unbalanced partitions: the pivots are being chosen badly.
            heapsort(slice);
            return;
        }
        depth -= 1;
        let p = partition(slice);
        let (left, rest) = slice.split_at_mut(p);
        let right = &mut rest[1..];
        if left.len() < right.len() {
            introsort(left, depth);
            slice = right;
        } else {
            introsort(right, depth);
            slice = left;
        }
    }
}

Heapsort

A max-heap is an array in which every element at index is at least as large as its children at and . Its largest element is at index 0. Floyd’s construction sifts down each internal node from the last to the first, building a heap in . Then, times, the root is swapped to the end of the unsorted part and the new root is sifted down, which costs . The total is for any input, in place.

pub fn heapsort<T: Ord>(slice: &mut [T]) {
    let n = slice.len();
    if n < 2 {
        return;
    }
    for start in (0..n / 2).rev() {
        sift_down(slice, start, n);
    }
    for end in (1..n).rev() {
        slice.swap(0, end);
        sift_down(slice, 0, end);
    }
}

fn sift_down<T: Ord>(s: &mut [T], mut root: usize, end: usize) {
    loop {
        let mut child = 2 * root + 1;
        if child >= end {
            return;
        }
        if child + 1 < end && s[child] < s[child + 1] {
            child += 1;
        }
        if s[root] >= s[child] {
            return;
        }
        s.swap(root, child);
        root = child;
    }
}

Heapsort jumps around the array, so it uses the cache poorly and is slower than quicksort in practice. It also makes about twice as many comparisons, since sifting down compares with both children at every level.

Shell’s method

Insertion sort is fast on nearly sorted data but moves each element one place at a time. Shell’s method first insertion-sorts the elements that are a large gap apart, then smaller gaps, finishing with gap 1, plain insertion sort on data that is by then nearly sorted. With Ciura’s gaps, extended by factors of 2.25 for large , it is a few lines of code and competitive up to tens of thousands of elements.

Figure 25.1. Comparisons.

Median-of-three quicksort settles near comparisons, within 20% of the lower bound. Heapsort tends to . Shell’s method grows faster than . Rust’s sort_unstable makes fewer comparisons than all three.

Table 25.1. Sorting one million keys in five arrangements.

one million 64-bit keysrandomnearly sortedsortedreversedthree distinct keys
quicksort56.0 ms6.0 ms4.1 ms4.2 ms12.1 ms
heapsort90.9 ms40.8 ms38.7 ms44.3 ms28.0 ms
Shell’s method100.4 ms72.3 ms6.8 ms11.3 ms13.7 ms
std sort_unstable11.3 ms11.5 ms0.2 ms0.3 ms1.2 ms
std sort (stable)13.9 ms9.5 ms0.2 ms0.3 ms1.3 ms

The standard library’s sorts are several times faster than these on random keys, and far faster on presorted input. They combine pattern detection, branch-free partitioning and careful small-sort networks, and they detect sorted runs, which makes already sorted input almost free. The library’s sorts are teaching implementations of the classic algorithms. For production sorting of primitive keys, use sort_unstable.

Algorithm

Quicksort of a range of keys, as an introsort.

  1. While the range holds more than 16 keys:
    • if this range has been reached through more than successive partitions, the pivots have been bad: sort it by heapsort and stop;
    • choose the pivot as the median of the first, middle and last keys;
    • partition (Hoare): move one index rightwards from the left end until it finds a key not less than the pivot, and another leftwards from the right end until it finds a key not greater than the pivot; if the indices have not crossed, swap the two keys and continue; when they cross, the range is split in two;
    • call quicksort on the smaller of the two parts, and continue this loop on the larger.
  2. Sort the remaining short range by insertion sort.

Sorting the smaller part by a call, and the larger by continuing the loop, limits the depth of the calls to .

The expected cost is comparisons, and the heapsort fallback makes that the worst case as well.

Insertion sort: for each key from the second on, shift the larger keys before it one place to the right, and put the key in the gap.

Heapsort.

  1. Build the heap. For each index from down to 0, sift down the element there: while it is smaller than its larger child, swap it with that child. Indices from on have no children and need no attention.
  2. Extract. For each end position from down to 1: swap the root, which is the largest remaining key, with the element at that position, and sift the new root down within the heap that is now one shorter.

Building the heap costs and the extraction , for every input.

Shell’s method.

  1. Build the list of gaps: Ciura’s sequence, extended by factors of 2.25 until the gap exceeds the length.
  2. For each gap from the largest that fits down to 1: perform an insertion sort in which each key is compared with, and moved past, the keys a gap apart instead of adjacent ones.

Implementation

pub fn shell_sort<T: Ord>(slice: &mut [T]) {
    let n = slice.len();
    let mut gaps: Vec<usize> = vec![1, 4, 10, 23, 57, 132, 301, 701];
    while *gaps.last().unwrap() < n {
        let next = (*gaps.last().unwrap() as f64 * 2.25) as usize;
        gaps.push(next);
    }
    for &gap in gaps.iter().rev() {
        if gap >= n {
            continue;
        }
        for i in gap..n {
            let mut j = i;
            while j >= gap && slice[j - gap] > slice[j] {
                slice.swap(j - gap, j);
                j -= gap;
            }
        }
    }
}
  • All three sort &mut [T] for any T: Ord; floating-point numbers, which are only PartialOrd, need a total-order key (see the example).
  • None allocates except Shell’s method, which keeps its short list of gaps.

In practice

//! Sorting with quicksort, heapsort and Shell's method.

use lib_jsl_sorting::{heapsort, quicksort, shell_sort};

fn main() {
    let words = ["pear", "fig", "apple", "kiwi", "banana", "cherry", "date", "apple"];
    let mut a = words.to_vec();
    quicksort(&mut a);
    println!("quicksort:      {a:?}");

    let mut temperatures = vec![21, -4, 15, 37, 0, 15, 8, -12, 29, 3];
    heapsort(&mut temperatures);
    println!("heapsort:       {temperatures:?}");

    // Any type with a total order works; here (surname, first name) pairs.
    let mut people = vec![("Noether", "Emmy"), ("Gauss", "Carl"), ("Euler", "Leonhard"), ("Gauss", "Anna")];
    shell_sort(&mut people);
    println!("Shell's method: {people:?}");

    // Floating-point numbers need a total order: sort their bit-level total ordering keys.
    let mut x = [2.5f64, -1.0, 0.0, 3.25, -7.5];
    let mut keys: Vec<i64> = x.iter().map(|v| { let b = v.to_bits() as i64; b ^ (((b >> 63) as u64) >> 1) as i64 }).collect();
    quicksort(&mut keys);
    for (slot, k) in x.iter_mut().zip(keys) {
        *slot = f64::from_bits((k ^ (((k >> 63) as u64) >> 1) as i64) as u64);
    }
    println!("floats:         {x:?}");
}
quicksort:      ["apple", "apple", "banana", "cherry", "date", "fig", "kiwi", "pear"]
heapsort:       [-12, -4, 0, 3, 8, 15, 15, 21, 29, 37]
Shell's method: [("Euler", "Leonhard"), ("Gauss", "Anna"), ("Gauss", "Carl"), ("Noether", "Emmy")]
floats:         [-7.5, -1.0, 0.0, 2.5, 3.25]

The two Gausses come out in first-name order because tuples compare field by field.

Strengths

  • Three classic in-place algorithms, generic over Ord; quicksort and heapsort are in the worst case.
  • Quicksort handles sorted, reversed and repeated keys in .

Weaknesses

  • None is stable, and Shell’s method has no proven bound.
  • All are several times slower than the standard library’s sorts.

Exercises

  1. Show that any comparison sort needs comparisons in the worst case, and estimate it with Stirling’s formula.
  2. Show that a partition sending all keys equal to the pivot to one side makes quicksort quadratic on equal keys, and that stopping both scans on equality fixes it.
  3. Prove that Floyd’s heap construction takes time.
  4. Show that -sorting an array that is already -sorted leaves it -sorted.
  5. Construct an input on which median-of-three quicksort without the heapsort fallback takes comparisons, and show that introsort’s depth limit keeps it to .
Hints and answers
  1. A decision tree that distinguishes the orderings has at least leaves, hence depth at least . Stirling gives .
  2. If all keys equal to the pivot go to one side, a run of equal keys is split into parts of sizes and at every level, so the cost is . Stopping both scans on equality swaps equal keys and splits the run near the middle, giving .
  3. Heap construction sifts down each internal node: a node at height costs , and there are at most such nodes, so the total is .
  4. The key lemma: if for every , then after sorting both sequences the -th smallest of is still the -th smallest of . -sorting sorts the chains ; apply the lemma to a chain and the chain shifted by positions, whose elements are pairwise those of the first because the array is -sorted.
  5. A median-of-three “killer” sequence makes every median-of-three pivot one of the smallest elements, so each partition removes only a constant number of keys, giving . Introsort switches to heapsort after levels, bounding the total at .

Further reading

  • C. A. R. Hoare, “Quicksort”, The Computer Journal 5 (1962) 10–16.
  • R. Sedgewick, “Implementing quicksort programs”, Communications of the ACM 21 (1978) 847–857.
  • J. W. J. Williams, “Algorithm 232: Heapsort”, Communications of the ACM 7 (1964) 347–348.
  • M. Ciura, “Best increments for the average case of Shellsort”, in Fundamentals of Computation Theory, LNCS 2138, Springer, 2001, 106–117.
  • D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed., Addison-Wesley, 1998, chapter 5.