Sort an array of 0s, 1s and 2s
Three pointers carve the array into four regions: settled 0s, settled 1s, unexamined, and settled 2s. A 0 swaps down, a 2 swaps up, a 1 stays. One pass, O(1) space — and the one subtlety is that after swapping a 2 the middle pointer must not advance.
Overview
The counting alternative
Count the 0s, 1s and 2s, then overwrite the array. Two passes, trivially correct, and usually the first answer. The question asks for one pass to rule it out — and because counting sort does not generalise to sorting objects by a three-way key, which the partition does.
Step through it
What to watch
- Four regions: settled 0s, settled 1s, unexamined, settled 2s.
- After swapping a 2 down,
midstays — the incoming value is unseen. - The loop ends when
midpasseshi, not the array end.
Say this out loud
"Dutch national flag. Three pointers - low, mid, high. 0 swaps to the low region and both advance, 2 swaps to the high region and only high moves, 1 just advances mid. One pass, O(1) space."