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.

Bubble sortstep 0
0 comparisons · 0 swaps
Selection sortstep 0
0 comparisons · 0 swaps
Insertion sortstep 0
0 comparisons · 0 swaps
Merge sortstep 0
0 comparisons · 0 writes
Quicksortstep 0
0 comparisons · 0 swaps
Heapsortstep 0
0 comparisons · 0 swaps

Each tick advances every algorithm by one recorded step (a comparison, swap or write).

At a glance

k is the range of key values, d the number of digits, b the base.

AlgorithmBestAverageWorstExtra spaceStable
Bubble sortO(n)O(n²)O(n²)O(1)Yes
Selection sortO(n²)O(n²)O(n²)O(1)No
Insertion sortO(n)O(n²)O(n²)O(1)Yes
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
QuicksortO(n log n)O(n log n)O(n²)O(log n)No
HeapsortO(n log n)O(n log n)O(n log n)O(1)No
Counting sortO(n + k)O(n + k)O(n + k)O(n + k)Yes
Radix sortO(d(n + b))O(d(n + b))O(d(n + b))O(n + b)Yes
TimsortO(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.

Bubble sort

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.

Insertion sort

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.

Selection sort

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.

Heapsort

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.

Merge sort

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.

Quicksort

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.

Counting sort

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.

Radix sort

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.

Timsort

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.