Efficient Sorting Algorithms

Lesson 7 of 20

Watch a pivot land in its final home and eight bars split, zip and merge into O(n log n) order.

The big picture

Divide and conquer

When n hits a million, O(n²) sorting needs a trillion comparisons. Divide and conquer gets there in about twenty million — split, solve the halves, zip them back.

n work × log n levels

Halving the problem log₂n times, with a linear pass at each level, gives O(n log n): 1,000,000 items take ~20 million steps instead of a trillion.

Merge sort

Split down to singles, then zip sorted halves together. Guaranteed O(n log n) and stable — but it pays O(n) auxiliary memory for the merge.

Quick sort

Pick a pivot, partition so everything ≤ pivot sits left and everything > pivot sits right, then recurse on both sides. In-place and cache-friendly.

Lomuto partition

One pass: i guards the ≤-zone, j scans. Each a[j] ≤ pivot grows the zone with a swap; one final swap drops the pivot between the zones — its forever home.

The catch

Quick sort degrades to O(n²) on sorted input with a last-element pivot; merge sort never degrades. std::sort is introsort: quicksort with a heapsort fallback.