Array techniquesAnimated
Dutch National Flag Algorithm
Partition an array into three groups in one pass with three pointers.
Time
O(n)
Extra space
O(1)
Use it for
Sorting 0/1/2 and 3-way partitioning.
How it works
- Sort an array of 0s, 1s and 2s in one pass without counting.
- Keep three pointers: low (end of the 0s), mid (the item being examined), high (start of the 2s).
- If a[mid] is 0, swap it with low and advance both. If 1, just advance mid. If 2, swap it with high and shrink high (do not advance mid: the swapped-in item is unchecked).
- Stop when mid passes high.
Watch it run
Loading animation…