Data Structures · Sorting

Sorting algorithms compared

Time and space costs for the eight sorts in this unit, with whether each one is stable and whether it sorts in place. Click a column heading to sort the table, and click an algorithm's name to open its interactive lab.

fast O(n) or O(n log n) between slower than n log n, faster than n² slow O(n²) digits depends on key length, not comparisons
Time
Algorithm Best Average Worst Extra space Stable In place Adaptive Good to know

Stable: values that compare equal keep their original order. This matters when you sort by one field after another, such as by name and then by grade.

In place: the sort rearranges the array itself, using only O(1) or O(log n) extra memory, instead of copying into a second array.

Adaptive: the sort runs faster when the input is already partly in order.

For radix sort: d is the number of digits in the largest key, and b is the base (10 for decimal digits).

Small or nearly sorted dataInsertion sort. It is simple, stable, in place, and close to O(n) when the data is almost in order.
General purpose, fast on averageQuick sort, with a good pivot choice (random or median of three) to avoid its O(n²) worst case.
Guaranteed O(n log n)Merge sort if you need it to be stable and can spare O(n) memory; heap sort if memory is tight.
Many integer keys with few digitsRadix sort. It never compares two keys, so it can beat the n log n limit that applies to comparison sorts.