QuickSort with Dutch National Flag 3-way partitioning and random pivot selection
Random pivot selection ensures that with high probability, each partition divides the array into reasonably balanced parts. Three-way partitioning handles duplicates by grouping equal elements together—excluded from recursion. For arrays with k distinct values, runtime approaches O(n log k).
The DNF partition transforms the O(n²) duplicate-heavy worst case into O(n) by processing all equal elements in one partition step.
Unlike merge sort (O(n) auxiliary space), quicksort partitions in-place. Space is dominated by the call stack. Tail-call optimization on the larger partition can guarantee O(log n) stack depth even in the worst case.
Introsort (used in std::sort) switches to heapsort when recursion exceeds 2⌊log n⌋, guaranteeing O(n log n) worst-case while preserving quicksort's cache efficiency.