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

Sorting and selection

Sorting puts data in order so that it can be searched, merged, ranked and grouped; selection finds part of that order without paying for all of it. This chapter covers lib_jsl_sorting:

  • three in-place comparison sorts: quicksort, heapsort and Shell’s method;
  • selecting the largest elements with a bounded heap;
  • grouping items into equivalence classes.

The central questions

  • Average or worst case? Quicksort is fastest on average, and falls back to heapsort, which guarantees , when its pivots go wrong; Shell’s method is simplest and adapts to nearly sorted data.
  • All of the order, or part of it? For the top of , a heap costs instead of .
  • The library or the standard library? Rust’s own sort and sort_unstable are faster than any of these on primitive keys, and stable when needed. The algorithms here are clear implementations of the classics, to read, compare and teach from.

Testing

Each sort is run on a million keys in five arrangements (random, nearly sorted, sorted, reversed, and only three distinct values), and its output is checked against the standard library’s. Comparisons are counted by sorting a key type whose Ord implementation counts its calls.

In the library

All of these are in lib_jsl_sorting (API reference).

You needUseEntry
A slice in orderquicksort, heapsort, shell_sortComparison sorting
The largest few elementsselect_m_largestSelection and equivalence classes
Groups of equivalent itemsequivalence_classesSelection and equivalence classes