Guide
Sorting algorithms compared, step by step, with real counts
Big-O tables tell you how sorting algorithms grow, but not how differently they behave on the input you actually have. Here we trace one algorithm by hand, then count the comparisons five classic algorithms make on the same 1,000 numbers in four different orders. The numbers explain why real languages use the hybrids they do.
Insertion sort, by hand
Insertion sort keeps a sorted prefix and inserts each next element into place by shifting larger elements one step right. Sorting [5, 2, 4, 6, 1, 3]:
| Step | Insert | Array after the step |
|---|---|---|
| start | 5 2 4 6 1 3 | |
| 1 | 2 | 2 5 4 6 1 3 |
| 2 | 4 | 2 4 5 6 1 3 |
| 3 | 6 | 2 4 5 6 1 3 (already in place) |
| 4 | 1 | 1 2 4 5 6 3 |
| 5 | 3 | 1 2 3 4 5 6 |
That took 12 comparisons. Step 3 cost a single comparison because 6 was already larger than everything before it, and that is the key property: insertion sort does almost no work on data that is nearly in order.
def insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # shift larger elements right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return aThe other four in one paragraph each
- Selection sort scans the unsorted part for the minimum and swaps it to the front. It always makes n(n−1)/2 comparisons, whatever the input, but only n − 1 swaps, which once mattered when writes were expensive.
- Merge sort splits the array in half, sorts each half recursively and merges the two sorted halves. Always O(n log n), stable, but needs O(n) extra memory for merging.
- Quicksort picks a pivot, partitions the array into elements smaller and larger than it, and recurses on both sides. Fast in practice and in place, but its running time depends on the pivot: a pivot that is always the smallest or largest element degrades it to O(n²).
- Heap sort builds a binary max-heap, then repeatedly moves the maximum to the end and restores the heap. Always O(n log n) and in place, but not stable, and its scattered memory access makes it slower than quicksort on real hardware.
Measured: 1,000 numbers, four orders
We counted the comparisons each algorithm made on the same 1,000 distinct numbers arranged four ways. The quicksort here is the textbook version that always picks the last element as the pivot, chosen on purpose to show the failure mode.
| Input | Insertion | Selection | Merge | Quicksort (last-element pivot) | Heap |
|---|---|---|---|---|---|
| Random | 242,506 | 499,500 | 8,714 | 12,555 | 16,865 |
| Already sorted | 999 | 499,500 | 4,932 | 499,500 | 17,583 |
| Reversed | 499,500 | 499,500 | 5,044 | 499,500 | 15,965 |
| Nearly sorted (10 swaps) | 8,009 | 499,500 | 6,423 | 150,781 | 17,561 |
- On random data, the O(n log n) algorithms win by a factor of 20 to 50 over the quadratic ones at only 1,000 elements, and the gap widens with n.
- On sorted input, insertion sort is the best of all (999 comparisons, one per element), while naive quicksort becomes as bad as selection sort. A pivot taken from the end of sorted data is always the maximum, so every partition is maximally lopsided.
- Selection sort does not care what it is given: exactly n(n−1)/2 = 499,500 every time.
- Merge sort and heap sort barely move between inputs: their cost is set by n, not by order.
Comparison counts are not running time. Heap sort makes fewer comparisons than quicksort on some inputs here and is still usually slower, because jumping around a heap misses the CPU cache far more than quicksort's sequential partitioning.
Complexity, stability and memory
| Algorithm | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|
| Insertion | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | No |
| Merge | 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) stack | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
Stability means equal elements keep their original order. It matters when you sort by one key after another: sort a list of people by name, then stably by city, and each city's people stay in name order. An unstable sort scrambles them.
What real languages actually use
No mainstream standard library uses any of these textbook versions directly. They combine them to keep each one's strength and avoid its weakness:
- Python (
list.sort,sorted) uses Timsort: it finds runs that are already in order, extends short runs with insertion sort, and merges runs. That is why sorting nearly sorted data in Python is so fast. Since Python 3.11 its merge order follows the Powersort policy. - Java sorts objects with TimSort (stable) and primitive arrays with Dual-Pivot Quicksort, where stability cannot be observed.
- C++
std::sortis usually introsort: quicksort with median-of-three pivots that switches to heap sort if recursion gets too deep (guaranteeing O(n log n)) and to insertion sort for small ranges.std::stable_sortis a merge sort. - JavaScript's
Array.prototype.sorthas been required to be stable since ECMAScript 2019; V8 implements it with TimSort.
Two patterns repeat. Every hybrid switches to insertion sort for small pieces, because its tiny overhead beats the O(n log n) algorithms below a few dozen elements, exactly as the table's sorted row suggests. And every quicksort-based sort guards its pivot choice, because the O(n²) row is not theoretical: sorted input is common in real data.
Which one to use
- In application code: your language's built-in sort. It is a tuned hybrid and almost certainly faster and safer than anything hand-written.
- In an interview or a contest: know merge sort and quicksort cold, including how to pick a pivot (random or median-of-three) and why.
- For tiny or nearly sorted arrays inside your own algorithm: insertion sort.
- When memory is tight and worst-case time matters: heap sort.
- When equal keys must keep their order: a stable sort (merge sort, Timsort).
Watching the swaps happen makes these differences stick faster than any table. DSA Visualizer plays sorting algorithms step by step and can run two side by side on the same data, and the problems on Code Sprout let you practise writing them against a judge. If your sort passes locally and fails there, how online judges decide a verdict explains why.