← back to algorithms

Sorting

Nievergelt & Hinrichs · Ch. 3 · Algorithms and Data Structures

Sorting is the gateway problem. Every comparison-based sort needs at least Ω(n log n) comparisons in the worst case. Merge sort and heapsort hit this bound. Quicksort hits it on average, with better constants.

split 38 27 43 3 9 82 10 38 27 43 3 9 82 10 38 27 43 3 merge 27 38 3 43 3 27 38 43 9 10 82 3 9 10 27 38 43 82

Insertion sort

Walk through the array left to right. For each element, slide it into its correct position among the already-sorted prefix. O(n²) worst case, but O(n) when the input is nearly sorted. Good for small arrays.

Scheme

Merge sort

Split in half, sort each half, merge. Always O(n log n). Uses O(n) extra space. Stable. The workhorse of external sorting.

Scheme

The n log n lower bound

Any comparison-based sort must make at least log_2(n!) comparisons in the worst case. By Stirling, log_2(n!) is Θ(n log n). You cannot do better with comparisons alone. Non-comparison sorts (counting sort, radix sort) beat this by using extra information about the keys.

Neighbors

Cross-references

  • 🪄 SICP — comparison: functional vs imperative approaches to the same algorithms