Sort array of 0s (red), 1s (white), and 2s (blue) in-place using three pointers
mid pointer traverses array left-to-rightmidmid > highThe invariant partitions the array into four regions: [0, low) contains 0s, [low, mid) contains 1s, (high, n-1] contains 2s, and [mid, high] is unprocessed. Each iteration shrinks the unprocessed region by at least one element, guaranteeing termination in exactly n steps.
Unlike comparison-based sorting (Ω(n log n)), three-way partitioning exploits the constraint of only three distinct values to achieve linear time.
low, mid, highThe algorithm achieves in-place partitioning by using the boundaries themselves to encode the sorted structure. No counting array or bucket storage is needed—the input array serves as both source and destination.
This is a "stable-ish" in-place algorithm: while not strictly stable, it preserves relative order within each color group better than random quicksort.