Dutch National Flag Sort in Java
Learn how Dutch National Flag Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Dutch National Flag Sort is a three-way partition. Given a middle value, it rearranges an array in a single pass into three parts: values less than the middle value on the left, values equal to it in the middle, and values greater than it on the right, like the three bands of the Dutch flag.
Three ideas carry the whole algorithm:
- Intended middle: the value that decides which of the three parts a value belongs to.
- Four regions: at any moment the array is split into “less”, “equal”, “unknown” and “greater”. The pass shrinks the unknown region by one value at every step.
- Three pointers:
imarks the end of the “less” part,jis the next unknown value, andkmarks the start of the “greater” part.
Edsger Dijkstra posed the problem in 1976: sort a row of red, white and blue balls using only swaps, looking at each ball once. When an array holds only three different values, the partition is a full sort, in linear time. The same partition is also the heart of 3-way QuickSort, where it keeps arrays with many duplicates fast, and it is a classic interview question, often in the form “sort an array of 0s, 1s and 2s”.
This article uses Dijkstra’s single-pass partition with three pointers, written as a generic method that compares any Comparable values with a given middle value.
Performance Characteristics
The algorithm makes exactly one pass over the array, so its cost depends only on the number of values, not on their order.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | Any input: every step settles one value |
| Average | $O(n)$ | Any input |
| Worst | $O(n)$ | Any input: at most $n$ steps, each with at most one swap |
Why $n$? Every pass through the loop either moves j one position right or moves k one position left, and the loop stops when they cross. The unknown region starts with $n$ values and loses one at every step, so there are at most $n$ steps.
The partition sorts the array only when it holds at most three different values, and the middle value is the middle one of the three. For general data it is a building block: 3-way QuickSort applies it recursively to the “less” and “greater” parts.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(1)$: three indices |
| In place | Yes |
| Stable | No (swaps move values past equal values in other parts) |
Algorithm (Pseudo Code)
The pass starts with every value unknown. It looks at the first unknown value. If it is less than the middle value, it is swapped to the end of the “less” part, and both that part and the scan move one step right. If it is greater, it is swapped with the last unknown value, at the start of the “greater” part, which grows one step to the left; the value that comes back is new, so it is checked next without moving on. If it is equal, it is already in the right place, and the scan simply moves on.
Each step settles one value, so the unknown region shrinks until the scan meets the “greater” part. At that point every value is in one of the three parts, and the pass is done. With only three different values, the three parts together are the sorted array.
1
2
3
4
5
6
7
8
9
10
dutchNationalFlagSort(array, intendedMiddle):
i = 0, j = 0, k = n - 1
while j <= k:
if array[j] < intendedMiddle:
swap(i, j), i++, j++
else if array[j] > intendedMiddle:
swap(j, k), k--
else:
j++
return array
At every step, array[0 .. i-1] is less than the middle value, array[i .. j-1] equals it, array[k+1 .. n-1] is greater than it, and only array[j .. k] is still unknown.
After swapping with
k, the code does not movej: the value that came from the right end hasn’t been checked yet. After swapping withi, it does movej, because the value that came back fromiis one thatjalready passed, so it must equal the middle value.
Visualization
The visualization below follows the Java code line by line, starting with ten values that are each 0, 1 or 2.
The Dutch National Flag problem is about three kinds of value, so instead of the values 0 to 9, the visualization starts with [2, 0, 1, 2, 1, 0, 0, 2, 1, 1] and calls sort(array, 1). Tick sort(array) on 0–9 to see what the one-argument sort does with the usual values 0 to 9.
Each step shows the array, the pointers and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with new random values.
- Pointers: I is
i, the end of the “less” part, J isj, the next unknown value, and K isk, the last unknown value before the “greater” part. - Colours: the value being checked, or the chosen middle element, is amber, the values being swapped are salmon, and values outside the unknown region
[j .. k], already in their part, are green. - Boundaries: the gray bars mark where the “equal” part starts (at
i) and where the “greater” part starts (afterk). The footer showsintendedMiddle. - sort(array) on 0–9: tick it to run the one-argument
sort, which uses the middle element of the array asintendedMiddle.
Java Code
The implementation is a DutchNationalFlagSort class with two public methods: sort(array), which partitions around the array’s middle element, and sort(array, intendedMiddle), which partitions around a given value. Both hand over to one private method, dutchNationalFlagSort, which does the three-pointer pass. Three small helpers, swap, less and greater, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
DutchNationalFlagSort.java, with the helpers inSortUtils.java.
sort(array)
1
2
3
4
5
6
7
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
return array;
}
return dutchNationalFlagSort(array, array[(int) Math.ceil((array.length) / 2.0) - 1]);
}
sort(array) is the entry point from the SortAlgorithm interface. It returns an empty array straight back. Otherwise it picks the element at the middle position, index ceil(n / 2) - 1, as the middle value, and partitions the array around it.
This method promises to sort, but it only partitions. The element at the middle position is not the middle value, and the “less” and “greater” parts are left in any order. For
[7, 2, 9, 4, 0, 8, 3, 6, 1, 5], the middle element is0, and the result is[0, 9, 4, 2, 8, 3, 6, 1, 5, 7]. Even with only three values,[2, 2, 1, 0, 0, 1]picks1and sorts, but[1, 2, 2, 0, 0, 1]picks2and leaves[1, 0, 0, 1, 2, 2]. For a guaranteed result, callsort(array, intendedMiddle)with the middle value of the three.
sort(array, intendedMiddle)
1
2
3
public <T extends Comparable<T>> T[] sort(T[] array, T intendedMiddle) {
return dutchNationalFlagSort(array, intendedMiddle);
}
The second sort lets the caller choose the middle value. That is the form the Dutch National Flag problem needs: for an array of 0s, 1s and 2s, pass 1. The middle value doesn’t have to occur in the array; then the “equal” part is simply empty.
dutchNationalFlagSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private <T extends Comparable<T>> T[] dutchNationalFlagSort(final T[] array, final T intendedMiddle) {
int i = 0;
int j = 0;
int k = array.length - 1;
while (j <= k) {
if (SortUtils.less(array[j], intendedMiddle)) {
SortUtils.swap(array, i, j);
j++;
i++;
} else if (SortUtils.greater(array[j], intendedMiddle)) {
SortUtils.swap(array, j, k);
k--;
} else {
j++;
}
}
return array;
}
dutchNationalFlagSort does the pass. i and j start at the left end and k at the right end, so the whole array starts as the unknown region [j .. k]. Each loop compares array[j] with the middle value: a smaller value is swapped to i and both pointers move right, a larger value is swapped to k and only k moves left, and an equal value just lets j move on. The loop ends when j passes k, and the array is returned, partitioned in place.
Two details are worth noticing:
- The values are compared with
compareTo, so their order is their natural order, not the order of the flag. Strings such as"red","white"and"blue"partition alphabetically: around"white", both"blue"and"red"count as “less”. To sort flag colours in flag order, use anenumdeclared in that order. - When
array[j]is less than the middle value andi == j,swapdoes nothing; the value is already at the end of the “less” part.
swap, less and greater
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) > 0;
}
These helpers from SortUtils keep the loop easy to read. swap exchanges two elements, and skips the work when both indices are the same. less and greater compare two elements with compareTo, so the partition works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {2, 0, 1, 2, 1, 0, 0, 2, 1, 1};
new DutchNationalFlagSort().sort(numbers, 1);
System.out.println(Arrays.toString(numbers));
// [0, 0, 0, 1, 1, 1, 1, 2, 2, 2]
Create a DutchNationalFlagSort and call sort with the middle value 1: the 0s, 1s and 2s come back in order, after a single pass. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Dutch National Flag Sort is a three-way partition: one pass splits the array into values less than, equal to and greater than a middle value.
- This implementation uses three pointers:
ifor the end of the “less” part,jfor the next unknown value, andkfor the start of the “greater” part. - At every step, only
array[j .. k]is unknown, and whenjpassesk, every value is in its part. - It runs in $O(n)$ time with $O(1)$ extra space, sorts in place but is not stable, and fully sorts only arrays with at most three different values, given the middle one.
- Use
sort(array, intendedMiddle)for 0s, 1s and 2s or other three-way splits. To sort general data, use the partition inside 3-way QuickSort, orArrays.sort().
