Comparison Sorting

Bubble, selection, insertion, merge, quick and heap sort — how each works, their trade-offs, and why n log n is the limit.

Intermediate 4 min readLesson 3 of 18 Interview Q&A

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:

InteractiveQuick sort
38
27
43
3
9
82
10
55
19
64
31
72
Time: O(n log n) avg · O(n²) worstSpace: O(log n)not stable
comparingswappingpivotsorted
Initial array
1/70

The cheat sheet

AlgorithmBestAverageWorstSpaceStableNotes
Bubblenn²n²1✓Teaching only
Selectionn²n²n²1✗Minimal swaps (n)
Insertionnn²n²1✓Great for small / nearly sorted data
Mergen log nn log nn log nn✓Predictable; linked lists; external sort
Quickn log nn log nn²log n✗Fastest in practice for arrays
Heapn log nn log nn log n1✗Guaranteed, in-place, cache-unfriendly
Timsortnn log nn log nn✓Python, Java objects, JS (V8)
Introsortn log nn log nn log nlog 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.
Insertion sort
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;
    }
}

Merge sort

Divide the array in half, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front element.

382738 2743343 338 27 43 3
Split down to single elements, then merge back up: [27 38] + [3 43] → [3 27 38 43].

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);
}

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; }

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, Java Arrays.sort(Object[])/Collections.sort, V8 Array.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.
Custom ordering
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] overflow
Key takeaways
  • 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.
Interview questions
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)).