Dutch national flag
Split an array into three groups in one pass with three pointers. Everything before low is in the first group, everything after high is in the last, and mid walks the unknown part in between, sending each value to its group with at most one swap.
How to recognise it
- The values fall into exactly three groups (0, 1, 2; below, inside, above a range; less, equal, greater than a pivot).
- You must rearrange in place, in one pass, with O(1) extra memory.
- Sorting an array with very few distinct values, or with many repeats.
The idea in one picture
Picture the Dutch flag: red, white, blue bands. You have a row of shuffled coloured tiles and want the three bands.
Keep the red band growing from the left and the blue band growing from the right. One finger (mid) walks through
the unsorted tiles in the middle. A red tile is swapped to the end of the red band, a blue tile to the front of the
blue band, and a white tile just stays. Each tile is handled once, so the whole job is one pass.
The invariant
| Region | Holds |
|---|---|
0 .. low - 1 | first group |
low .. mid - 1 | middle group |
mid .. high | not looked at yet |
high + 1 .. n - 1 | last group |
Template
low = 0, mid = 0, high = n - 1
while mid <= high:
if nums[mid] is in the first group:
swap nums[low], nums[mid]; low = low + 1; mid = mid + 1
else if nums[mid] is in the last group:
swap nums[mid], nums[high]; high = high - 1 # mid stays: new value is unknown
else:
mid = mid + 1
A guided example: sort [2, 0, 2, 1, 1, 0]
| step | low | mid | high | array | action |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 5 | [2, 0, 2, 1, 1, 0] | 2: swap with high |
| 2 | 0 | 0 | 4 | [0, 0, 2, 1, 1, 2] | 0: swap with low |
| 3 | 1 | 1 | 4 | [0, 0, 2, 1, 1, 2] | 0: swap with low |
| 4 | 2 | 2 | 4 | [0, 0, 2, 1, 1, 2] | 2: swap with high |
| 5 | 2 | 2 | 3 | [0, 0, 1, 1, 2, 2] | 1: move on |
| 6 | 2 | 3 | 3 | [0, 0, 1, 1, 2, 2] | 1: move on, done |
Common mistakes
- Moving
midforwards after swapping withhigh, which skips a value that was never checked. - Looping while
mid < highinstead ofmid <= high, which leaves the last unknown value unchecked. - Counting the three values and rewriting the array. That works for 0, 1, 2 but needs two passes, and it fails when the groups are ranges of different values that must be kept.
Problems
- Sort Colorsmediumguide ready
- Three way partitioning of an array around a given valuemediumguide ready
- Partitioning and Sorting Arrays with Many Repeated Entriesmediumguide ready