SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

Basic Algorithms: Merge Sort, Quicksort and How Java Really Sorts

Two O(n log n) divide-and-conquer sorts, how to defuse quicksort's worst case, and why Arrays.sort uses dual-pivot quicksort for primitives but TimSort for objects.

17 Nov 20267 min readMid

–

With a million elements, the O(n²) sorts from part 1 need about 10¹² operations, roughly an hour of work. Divide and conquer (split, solve the pieces with recursion, combine) gets it down to O(n log n); then come Arrays.sort and the Comparator traps.

1. The problem

A job sorts 1 million orders by id with a hand-written quick sort, pivot = last element. The ids are already ascending: each partition removes just one element, n + (n-1) + ... + 1 comparisons, and the job runs for tens of minutes before a StackOverflowError.

2. Key idea

Merge sort: split in half, sort each half, merge with two pointers (O(n) per level, log₂ n levels). Comparing with <= takes equal elements from the left first: that's what makes it stable. Quick sort: pick a pivot, move smaller to the left and larger to the right, recurse on both sides; no merge step.

Algorithm Average Worst Extra memory Stable
Insertion O(n²) O(n²) O(1) yes; good for small, nearly sorted arrays
Merge O(n log n) O(n log n) O(n) yes
Quick O(n log n) O(n²) O(log n) no
Counting / Radix O(n + k) O(n + k) O(n + k) yes
TimSort O(n log n), best O(n) O(n log n) O(n) yes

Why Ω(n log n): there are n! permutations and each comparison yields 1 bit, so you need at least log₂(n!) ≈ n log₂ n comparisons.

2.1 Defeating quick sort's worst case

Problem Fix
Bad pivot on sorted data random pivot or median-of-three
Many duplicates (Lomuto degrades to O(n²)) 3-way partitioning: <, =, > pivot
O(n) recursion depth recurse into the smaller half: depth ≤ log₂ n

2.2 How does Java actually sort?

API Algorithm Why
Arrays.sort(int[]) Dual-Pivot Quicksort, O(n log n) worst case since Java 14 equal primitives are indistinguishable, no stability needed
Arrays.sort(Object[]), List.sort TimSort: find existing runs, merge them objects need stability

Sort where the data lives: ORDER BY ... LIMIT 20 with an index reads 20 rows.

3. In Java

JAVA
static void quickSort3Way(int[] a, int lo, int hi) {
    if (lo >= hi) return;
    int pivot = a[ThreadLocalRandom.current().nextInt(lo, hi + 1)];   // random pivot
    int lt = lo, i = lo, gt = hi;
    while (i <= gt) {
        if (a[i] < pivot) swap(a, lt++, i++);
        else if (a[i] > pivot) swap(a, i, gt--);
        else i++;                                                     // equal: stays in the middle
    }
    quickSort3Way(a, lo, lt - 1);
    quickSort3Way(a, gt + 1, hi);
}
// 1 million sorted elements: O(n log n); 1 million identical elements: one O(n) pass
 
Comparator<Integer> bad = (x, y) -> x - y;
bad.compare(Integer.MIN_VALUE, 1);              // 2147483647: claims MIN_VALUE > 1
Comparator<Integer> good = Integer::compare;

Other languages: Python's sorted uses TimSort; Go's sort.Slice isn't stable.

Merge sort for data larger than RAM

Databases use external merge sort when an ORDER BY doesn't fit work_mem (PostgreSQL) or sort_buffer_size (MySQL): sort memory-sized chunks, write them to disk, then do a k-way merge with a heap. "external merge" in EXPLAIN ANALYZE is the sign.

Merge sort also suits linked lists (no O(n) buffer) and parallelizes easily since the halves are independent. When hand-writing it, allocate the buffer once for all levels, and skip the merge when a[mid] <= a[mid + 1] so sorted input costs only O(n).

4. Working with AI

Give the AI: hand-written sorts when built-ins are banned, multi-key comparators, tests with sorted arrays, all-duplicate arrays, arrays containing Integer.MIN_VALUE.

Check in AI-written code:

  • Quick sort uses a random or median-of-three pivot and handles duplicates.
  • Comparators use Integer.compare or comparingInt, not a - b.
  • Comparators don't read the clock or random values; null goes through nullsFirst/nullsLast.
  • No pulling a whole table up to sort when ORDER BY ... LIMIT would do.

5. Exercises

Exercise 1: A multi-key comparator

Sort employees (department, salary, name) by department ascending, then salary descending, then name. The AI writes:

JAVA
employees.sort(Comparator.comparing(Employee::department)
        .thenComparing(Employee::salary)
        .thenComparing(Employee::name)
        .reversed());

How is the result wrong? Fix it.

Solution to Exercise 1

.reversed() at the end reverses the whole chain: departments become descending, names too. Reverse only the salary key:

JAVA
employees.sort(Comparator.comparing(Employee::department)
        .thenComparing(Employee::salary, Comparator.reverseOrder())
        .thenComparing(Employee::name));

Exercise 2: A production-only failure

A ranking job throws IllegalArgumentException: Comparison method violates its general contract!, only in production with a few hundred thousand rows; tests with 50 rows always pass. The comparator compares a double score with a.score < b.score ? -1 : 1. Diagnose and fix.

Solution to Exercise 2

The comparator never returns 0, so compare(a, b) and compare(b, a) are both 1 for equal scores: symmetry is broken. With NaN, every < is false, breaking transitivity too. TimSort only detects the inconsistency in a few merge branches that run when runs are long enough, so small data hides it.

Fix: Comparator.comparingDouble(Item::score) (it uses Double.compare, handling NaN and -0.0). Add a test with large data and many equal scores.

Summary

  • Merge sort is always O(n log n), stable thanks to <= when merging.
  • Quick sort is fast but needs a random pivot and 3-way partitioning.
  • Comparison sorts need Ω(n log n); counting/radix beat it by not comparing.
  • Java: primitives use Dual-Pivot Quicksort, objects use TimSort.
  • Comparators: no a - b; they must be symmetric and transitive.

Read more: Big-O and O(n²) sorts.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…
Next on the roadmapAlgorithm practice: recursion, sorting and turning recursion into loops