Efficient Sorting Algorithms

Lesson 7 of 20

Split [9,4,7,1,8,5] down to atoms, merge it back sorted — and watch a pivot re-partition the array around itself.

The big picture

Divide and conquer

The O(n²) basics grow a sorted region one element at a time. The fast sorts split the whole problem in half — and halving is what turns quadratic into n log n.

Merge sort: guaranteed

Split to single elements, merge sorted halves upward. O(n log n) on every input, stable — but it needs an O(n) auxiliary array.

Quicksort: pivot rule

Partition around a pivot, park it, recurse on both sides. Average O(n log n) in-place with tiny constants; worst case O(n²).

Lomuto partition

Pivot = last element. i banks everything ≤ pivot on the left; the pivot finally lands at p = i + 1, done forever.

Java ships both ideas

Arrays.sort(int[]) runs dual-pivot quicksort on primitives; object arrays get TimSort — a stable merge-sort hybrid.

The halving math

log₂(1,000,000) ≈ 20 levels. A million elements sort in about 20 rounds of linear work, not a million sweeps.