How do selection-sort, insertion-sort, heap-sort, merge-sort and quick-sort compare, and which inputs suit each?
The two simple sorts are $O(n^2)$ and in place, good for small inputs. For large inputs: heap-sort ($O(n \log n)$, in place), merge-sort ($O(n \log n)$, stable, sequential access, for huge inputs) and quick-sort ($O(n \log n)$ expected, in place, usually the fastest).
| Algorithm | Time | Notes |
|---|---|---|
| selection-sort | $O(n^2)$ | in place; slow, good for small inputs |
| insertion-sort | $O(n^2)$ | in place; slow, good for small inputs, fast on nearly sorted ones |
| heap-sort | $O(n \log n)$ | in place; fast, good for large inputs |
| merge-sort | $O(n \log n)$ | sequential data access, stable; fast, good for huge inputs |
| quick-sort | $O(n \log n)$ expected | in place; the fastest in practice, good for large inputs |
How to read "good for": the $O(n^2)$ sorts have the smallest constant factors, so for a few dozen elements they beat the $O(n \log n)$ algorithms, which is why fast library sorts switch to insertion-sort for small pieces. Heap-sort guarantees $O(n \log n)$ in place but jumps around the array a lot. Merge-sort's sequential access makes it the one for data that does not fit into memory. Quick-sort has the tightest inner loop and wins on large arrays in memory, provided its pivots are chosen sensibly.
Go deeper:
Sorting algorithm: comparison of algorithms — best, average and worst case, memory and stability of the common sorts in one table.
Sorting algorithms animations (Toptal) — the same algorithms racing on random, nearly sorted, reversed and few-unique inputs.