Dutch National Flag (Sort Colors)
Sort an array of 0s, 1s and 2s in a single pass, in place, with three markers.
Given an array numsnums
Example 1
Example 2
The Idea
The flag of the Netherlands has three bands: red, white and blue. Picture a shuffled row of red, white and blue cards that you want to lay out like that flag, red on the left, white in the middle, blue on the right. The Dutch computer scientist Edsger Dijkstra posed the problem this way, which is where its name comes from. In the array, red is 0, white is 1 and blue is 2.
Any general sorting method would do the job, but this array is unusual: it holds only three different values. Each value already tells you where it belongs. A 0 goes to the left end, a 2 goes to the right end, and a 1 goes in between. So can every value be put in its place in a single walk through the array?
Try it on Example 1, [2, 0, 2, 1, 1, 0]lohimid
The three markers split the array into four regions. The 0s sit left of lolomidmidhihi
In the row labelled start, every cell is white, because nothing has been checked yet. The value at midhihi
The swap brought the 0 from index 5 to index 0, and it still has the orange outline. The marker midmidlolomid
Row 4 sends the 2 at index 2 to index 4 and brings back a 1. In rows 5 and 6, midmidmidmidhi[0, 0, 1, 1, 2, 2]
Each step either moved midhi
Solution Approach
A simpler way counts the values in two passes. The one-pass walk needs three decisions: what to do with each value at midmidhi
Counting first, in two passes
Is a full sort needed at all? A general sort such as Arrays.sort
That takes O(n) time too, but it reads the array twice and writes new numbers over the old ones instead of moving them. If each value were the colour of a larger record, writing a 0 would not bring the record along. The walk in the picture moves the values themselves with swaps, in one pass.
Handling a 0, a 1 and a 2
What should happen to the value at midlolomidlolomid
A 1 is already in the right place, because the teal region ends just before midmidhihi
Why mid waits after a swap with hi
Why not move midhilomid[1, 2, 0][1, 0, 2]
When the walk stops
How long does the walk go on? As long as mid <= himid < hi[1, 0][1, 0]midhi
Java Solution
The method sortColors
- First, set the three markers:
andlo start at index 0, andmid starts athi , the last index. The comment beside each one says which region it closes off.nums.length - 1 - Then a
loop runs as long aswhile , that is, while some value is still unchecked. Each time round, it looks atmid <= hi .nums[mid] - For a 0, it calls the helper
, which exchanges the values at two indexes of the array, and movesswap(nums, lo, mid) andlo forward.mid - For a 1, it only moves
forward.mid - For a 2, it calls
and movesswap(nums, mid, hi) back, leavinghi on the value that just arrived.mid - When the loop ends, the method has nothing to return, because it has rearranged
itself.nums
The main[2, 2, 1, 1, 0, 0]
import java.util.Arrays;
public class SortColors {
public static void sortColors(int[] nums) {
int lo = 0; // nums[0 .. lo-1] are all 0
int mid = 0; // nums[lo .. mid-1] are all 1
int hi = nums.length - 1; // nums[hi+1 .. n-1] are all 2
while (mid <= hi) {
if (nums[mid] == 0) {
swap(nums, lo, mid);
lo++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums, mid, hi);
hi--; // mid stays: the value swapped in is not checked yet
}
}
}
private static void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
public static void main(String[] args) {
int[][] inputs = {
{2, 0, 2, 1, 1, 0},
{2, 0, 1},
{},
{1},
{2, 2, 2},
{2, 2, 1, 1, 0, 0},
};
for (int[] nums : inputs) {
String before = Arrays.toString(nums);
sortColors(nums);
System.out.println(before + " -> " + Arrays.toString(nums));
}
}
}
Running it prints:
[2, 0, 2, 1, 1, 0] -> [0, 0, 1, 1, 2, 2]
[2, 0, 1] -> [0, 1, 2]
[] -> []
[1] -> [1]
[2, 2, 2] -> [2, 2, 2]
[2, 2, 1, 1, 0, 0] -> [0, 0, 1, 1, 2, 2]
Both examples come out as expected: [0, 0, 1, 1, 2, 2][0, 1, 2][] -> []himid <= hi
Now look at [2, 2, 2] -> [2, 2, 2]midhihihi
Would two equal values keep their starting order? Look back at the picture. The 0 that starts at index 5 ends at index 0, ahead of the 0 that starts at index 1. The 2 that starts at index 0 ends at index 5, behind the 2 from index 2. So the sort is not stable: equal values can trade places. For plain numbers it makes no difference, since one 0 cannot be told from another.
Complexity
Every step of the loop shrinks the unchecked region by one cell, and nothing grows with the input except the array itself.
- Time: O(n) in the best, average and worst case, because each step moves
forward ormid back, so the loop runs exactly n times for n values in any order. The order only changes the number of swaps: on six values, a run made none for only 1s, four for Example 1, and six for only 0s or only 2s.hi - Space: O(1), because the sort works in place, keeping just the three markers and the one temporary value inside
.swap
The same split into "less than, equal to, greater than" helps