Sorting algorithms
From bubble sort to Timsort: how each algorithm works, step by step, what it costs, and which one your language actually uses.
Sorting race
Six comparison sorts on the same 24 values. Try different inputs: nearly sorted data changes the ranking completely.
At a glance
k is the range of key values, d the number of digits, b the base.
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heapsort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes |
| Radix sort | O(d(n + b)) | O(d(n + b)) | O(d(n + b)) | O(n + b) | Yes |
| Timsort | O(n) | O(n log n) | O(n log n) | O(n) | Yes |
Simple sorts
Easy to understand, quadratic time; fine for small or nearly sorted data.
Repeatedly swap adjacent values that are out of order until a full pass makes no swaps: simple to understand, O(n²), and almost never the right choice.
Take each value and slide it left into its place among the already-sorted values: O(n²) in general, but very fast on small or nearly sorted arrays.
Find the smallest remaining value and swap it into place, one position at a time: always O(n²) comparisons, but at most n − 1 swaps.
Efficient comparison sorts
O(n log n) sorts that compare elements.
Turn the array into a max-heap, then repeatedly move the largest value to the end: guaranteed O(n log n) with O(1) extra memory, but not stable.
Split the array in half, sort each half, then merge them: a guaranteed O(n log n), stable sort, and the basis for sorting data too big for memory.
Pick a pivot, partition the array into smaller and larger values around it, then sort each side the same way: O(n log n) on average, in place.
Non-comparison sorts
Beat n log n by exploiting the shape of the keys.
Count how many times each key value occurs, then write the values back in order: O(n + k) time for small integer keys, with no comparisons at all.
Sort integers digit by digit, from least to most significant, using a stable counting sort on each digit: O(d · n) for d-digit keys.
Sorting in practice
What real languages and libraries use, and why.
The merge sort and insertion sort hybrid behind Python, Java and V8's built-in sorts: stable, O(n log n), and very fast on partly ordered data.