Comparison Sorting
Bubble, selection, insertion, merge, quick and heap sort — how each works, their trade-offs, and why n log n is the limit.
Sorting puts elements in order. It matters because sorted data unlocks faster algorithms — binary search, two pointers, deduplication, merging, interval problems — and because sorting is a component of almost everything from databases (ORDER BY, sort-merge joins) to graphics.
Pick an algorithm below and step through it:
The cheat sheet
| Algorithm | Best | Average | Worst | Space | Stable | Notes |
|---|---|---|---|---|---|---|
| Bubble | n | n² | n² | 1 | ✓ | Teaching only |
| Selection | n² | n² | n² | 1 | ✗ | Minimal swaps (n) |
| Insertion | n | n² | n² | 1 | ✓ | Great for small / nearly sorted data |
| Merge | n log n | n log n | n log n | n | ✓ | Predictable; linked lists; external sort |
| Quick | n log n | n log n | n² | log n | ✗ | Fastest in practice for arrays |
| Heap | n log n | n log n | n log n | 1 | ✗ | Guaranteed, in-place, cache-unfriendly |
| Timsort | n | n log n | n log n | n | ✓ | Python, Java objects, JS (V8) |
| Introsort | n log n | n log n | n log n | log n | ✗ | C++ std::sort |
Stable means equal elements keep their original relative order — essential when sorting by multiple keys (sort by name, then stable-sort by department).
The simple O(n²) sorts
- Bubble sort repeatedly swaps adjacent out-of-order pairs; each pass bubbles the largest remaining element to the end.
- Selection sort repeatedly selects the minimum of the unsorted part and swaps it into place.
- Insertion sort grows a sorted prefix, inserting each new element by shifting larger ones right — exactly how you sort playing cards. It's O(n) on nearly sorted input, which is why real-world hybrids use it for small subarrays.
void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; // shift right
j--;
}
a[j + 1] = key;
}
}def insertion_sort(a):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j] # shift right
j -= 1
a[j + 1] = keyfunction insertionSort(a: number[]) {
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
}Merge sort
Divide the array in half, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front element.
There are log₂ n levels and each level does O(n) merging work → O(n log n) always. It needs O(n) extra space for arrays, is stable, and is ideal for linked lists (merging needs no random access) and external sorting of data larger than RAM.
void mergeSort(int[] a, int l, int r, int[] tmp) {
if (l >= r) return;
int m = (l + r) >>> 1;
mergeSort(a, l, m, tmp);
mergeSort(a, m + 1, r, tmp);
int i = l, j = m + 1, k = l;
while (i <= m && j <= r) tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++]; // <= keeps it stable
while (i <= m) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
System.arraycopy(tmp, l, a, l, r - l + 1);
}def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps it stable
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
out.extend(left[i:])
out.extend(right[j:])
return outfunction mergeSort(a: number[]): number[] {
if (a.length <= 1) return a;
const mid = a.length >> 1;
const left = mergeSort(a.slice(0, mid)), right = mergeSort(a.slice(mid));
const out: number[] = [];
let i = 0, j = 0;
while (i < left.length && j < right.length)
out.push(left[i] <= right[j] ? left[i++] : right[j++]);
return out.concat(left.slice(i), right.slice(j));
}Quicksort
Pick a pivot, partition the array so smaller elements go left and larger go right (the pivot lands in its final spot), then recurse on both sides. All the work happens in partitioning; there's no merge step.
void quickSort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int p = partition(a, lo, hi);
quickSort(a, lo, p - 1);
quickSort(a, p + 1, hi);
}
int partition(int[] a, int lo, int hi) { // Lomuto scheme
int r = lo + (int) (Math.random() * (hi - lo + 1));
swap(a, r, hi); // random pivot avoids the O(n²) worst case
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; j++)
if (a[j] < pivot) swap(a, i++, j);
swap(a, i, hi);
return i;
}
void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }import random
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r] # random pivot
pivot, i = a[hi], lo
for j in range(lo, hi): # Lomuto partition
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)function quickSort(a: number[], lo = 0, hi = a.length - 1): void {
if (lo >= hi) return;
const r = lo + Math.floor(Math.random() * (hi - lo + 1));
[a[r], a[hi]] = [a[hi], a[r]]; // random pivot
const pivot = a[hi];
let i = lo;
for (let j = lo; j < hi; j++)
if (a[j] < pivot) { [a[i], a[j]] = [a[j], a[i]]; i++; }
[a[i], a[hi]] = [a[hi], a[i]];
quickSort(a, lo, i - 1);
quickSort(a, i + 1, hi);
}Why quicksort is usually fastest: it sorts in place with sequential, cache-friendly scans and a tight inner loop. Merge sort moves data to a buffer; heap sort jumps around memory.
The Ω(n log n) lower bound
Any algorithm that sorts only by comparing elements needs Ω(n log n) comparisons in the worst case. A comparison sort is a binary decision tree whose leaves are the n! possible orderings; a binary tree with n! leaves has height at least log₂(n!) ≈ n log₂ n. To beat it you must use more than comparisons — see Linear-time sorting.
What languages actually use
- Python
sorted/list.sort, JavaArrays.sort(Object[])/Collections.sort, V8Array.prototype.sort: Timsort (stable). It finds existing ascending/descending "runs", extends short runs with insertion sort, and merges them — O(n) on already-sorted data. - Java
Arrays.sort(int[]): dual-pivot quicksort (primitives don't need stability). - C++
std::sort: introsort;std::stable_sort: merge sort.
people.sort(Comparator.comparing(Person::dept).thenComparing(Person::age, Comparator.reverseOrder()));
int[][] intervals = ...;
Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0])); // avoid x[0]-y[0] overflowpeople.sort(key=lambda p: (p.dept, -p.age))
intervals.sort(key=lambda iv: iv[0])people.sort((a, b) => a.dept.localeCompare(b.dept) || b.age - a.age);
nums.sort((a, b) => a - b); // default sort compares as STRINGS: [10, 9, 1].sort() → [1, 10, 9]- O(n²) sorts are for tiny or nearly sorted inputs; insertion sort is the useful one.
- Merge sort: guaranteed O(n log n), stable, O(n) space. Quicksort: fastest on average, in place, O(n²) worst unless the pivot is randomised.
- Heap sort: O(n log n) and O(1) space, but slower in practice.
- Comparison sorting is Ω(n log n). Real libraries use hybrids: Timsort, introsort.
QSort an array of 0s, 1s and 2s in one pass.medium
Dutch national flag: pointers low, mid, high. If a[mid] is 0, swap with low and advance both; if 1, advance mid; if 2, swap with high and decrement high (don't advance mid). O(n), O(1) space.
QWhich sort would you use for a linked list?medium
Merge sort: find the middle with fast/slow pointers, sort both halves, merge by relinking nodes. O(n log n) time and O(log n) recursion space (O(1) bottom-up) — no random access needed.
QHow do you sort 100 GB of data with 4 GB of RAM?hard
External merge sort: read 4 GB chunks, sort each in memory and write it out as a sorted run (25 runs). Then k-way merge the runs with a min-heap, streaming through small buffers per run and writing the output sequentially.
QFind the k-th smallest element without fully sorting.medium
Quickselect: partition as in quicksort, then recurse only into the side containing index k. Average O(n), worst O(n²) (randomise the pivot; median-of-medians guarantees O(n)).