Sort an Array of 0s, 1s and 2s Without Sorting: Dutch National Flag Algorithm
Sort an array containing only 0, 1 and 2 in one pass without any sorting algorithm. Learn the Dutch National Flag algorithm with an animated dry run and code in Java, C, C++, JavaScript and Python.
"Sort an array of 0s, 1s and 2s without using a sorting algorithm" is a favourite interview question, also known as Sort Colors or the Dutch National Flag problem. The trick is to use what you know about the data: there are only three possible values. In this post you will learn how to think about it, see a simple counting solution, and then master the one-pass three pointer algorithm with an animated dry run and code in Java, C, C++, JavaScript and Python.
Problem statement#
Given an array arr that contains only the values 0, 1 and 2, sort it in ascending order in place, without using any sorting algorithm or library sort.
Input: [0, 1, 2, 0, 1, 2, 1, 0]
Output: [0, 0, 0, 1, 1, 1, 2, 2]
Input: [2, 0, 1]
Output: [0, 1, 2]How to think about this problem#
A general sorting algorithm takes O(n log n) because it can't assume anything about the values. Here we know a lot: there are only three distinct values. So we are not really sorting, we are grouping.
Picture the final array as three zones: all 0s on the left, all 1s in the middle, all 2s on the right. Now imagine walking through the array once and, for each element, throwing it into the correct zone:
- A
0should be thrown to the left end. - A
2should be thrown to the right end. - A
1can stay where it is; it will naturally end up in the middle.
To throw values to the ends we need to know where each zone currently ends. That is three pointers: low (end of the 0s zone), mid (the element we are looking at) and high (start of the 2s zone).
Approaches#
Approach 1: Count and overwrite (two passes)#
Count how many 0s, 1s and 2s there are in a first pass. In a second pass, write that many 0s, then 1s, then 2s. This is O(n) time and O(1) space and perfectly valid. Its weakness is that it needs two passes and only works because the values carry no extra data.
Approach 2: Dutch National Flag (one pass, optimal)#
Keep three regions while you scan:
[ 0 0 0 | 1 1 1 | ? ? ? ? | 2 2 2 ]
0 low mid high n-1
arr[0 .. low-1] are all 0
arr[low .. mid-1] are all 1
arr[mid .. high] are not checked yet
arr[high+1 .. n-1] are all 2- Start with
low = 0,mid = 0,high = n - 1. - While
mid <= high, look atarr[mid]:- If it is 0: swap it with
arr[low], then move bothlowandmidforward. - If it is 1: it is already in the middle zone, so just move
midforward. - If it is 2: swap it with
arr[high]and movehighback. Do not movemid, because the value that just arrived fromhighhasn't been checked yet.
- If it is 0: swap it with
- When
midpasseshigh, the unknown region is empty and the array is sorted.
| Approach | Time | Extra space | Passes |
|---|---|---|---|
| Library sort | O(n log n) | O(1) to O(n) | Not allowed here |
| Counting | O(n) | O(1) | 2 |
| Dutch National Flag | O(n) | O(1) | 1 |
Dry run (animated)#
The Dutch National Flag algorithm on a short example, [2, 0, 1, 2, 1, 0]. Blue boxes are finished 0s, red boxes are finished 2s, and the pointers show low, mid and high.
arr[mid] = 2: swap witharr[high], giving[0, 0, 1, 2, 1, 2].highmoves to 4.arr[mid] = 0: swap witharr[low](itself).lowandmidmove to 1.arr[mid] = 0: same again.lowandmidmove to 2.arr[mid] = 1: just movemidto 3.arr[mid] = 2: swap witharr[high], giving[0, 0, 1, 1, 2, 2].highmoves to 3.arr[mid] = 1: movemidto 4. Nowmid > high, so we stop. Sorted in one pass.
Code#
Java#
import java.util.Arrays;
public class Main {
static void sort012(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
if (arr[mid] == 0) {
int t = arr[low]; arr[low] = arr[mid]; arr[mid] = t;
low++;
mid++;
} else if (arr[mid] == 1) {
mid++;
} else { // arr[mid] == 2
int t = arr[mid]; arr[mid] = arr[high]; arr[high] = t;
high--;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 0, 1, 2, 1, 0};
sort012(arr);
System.out.println(Arrays.toString(arr)); // [0, 0, 0, 1, 1, 1, 2, 2]
}
}C#
#include <stdio.h>
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
void sort012(int arr[], int n) {
int low = 0, mid = 0, high = n - 1;
while (mid <= high) {
if (arr[mid] == 0) {
swap(&arr[low], &arr[mid]);
low++;
mid++;
} else if (arr[mid] == 1) {
mid++;
} else { /* arr[mid] == 2 */
swap(&arr[mid], &arr[high]);
high--;
}
}
}
int main(void) {
int arr[] = {0, 1, 2, 0, 1, 2, 1, 0};
int n = sizeof(arr) / sizeof(arr[0]);
sort012(arr, n);
for (int i = 0; i < n; i++) printf("%d ", arr[i]); /* 0 0 0 1 1 1 2 2 */
printf("\n");
return 0;
}C++#
#include <iostream>
#include <vector>
using namespace std;
void sort012(vector<int>& arr) {
int low = 0, mid = 0, high = (int)arr.size() - 1;
while (mid <= high) {
if (arr[mid] == 0) {
swap(arr[low++], arr[mid++]);
} else if (arr[mid] == 1) {
mid++;
} else { // arr[mid] == 2
swap(arr[mid], arr[high--]);
}
}
}
int main() {
vector<int> arr = {0, 1, 2, 0, 1, 2, 1, 0};
sort012(arr);
for (int x : arr) cout << x << " "; // 0 0 0 1 1 1 2 2
cout << endl;
return 0;
}JavaScript#
function sort012(arr) {
let low = 0;
let mid = 0;
let high = arr.length - 1;
while (mid <= high) {
if (arr[mid] === 0) {
[arr[low], arr[mid]] = [arr[mid], arr[low]];
low++;
mid++;
} else if (arr[mid] === 1) {
mid++;
} else {
// arr[mid] === 2
[arr[mid], arr[high]] = [arr[high], arr[mid]];
high--;
}
}
return arr;
}
console.log(sort012([0, 1, 2, 0, 1, 2, 1, 0]).join(" ")); // 0 0 0 1 1 1 2 2Python#
def sort012(arr):
low = mid = 0
high = len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else: # arr[mid] == 2
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr
print(*sort012([0, 1, 2, 0, 1, 2, 1, 0])) # 0 0 0 1 1 1 2 2Complexity analysis#
- Time: O(n). Every step either moves
midforward or moveshighback, so the unknown region shrinks by one each time. At mostnsteps. - Space: O(1). Three pointers, no matter how big the array is.
Edge cases and common mistakes#
- Moving
midafter swapping withhigh: this is the most common bug. The value that came fromhighcould be a 0 or a 2 and must be checked first. - Using
mid < highinstead ofmid <= high: the last unchecked element is skipped and the array can stay unsorted, for example[1, 0]. - Why is it safe to move
midafter swapping withlow? Everything betweenlowandmid - 1is already a 1, so the value that comes back fromlowis a 1 (or the same 0 whenlow == mid). - Already sorted, all 0s, all 2s, or an empty array: all handled correctly by the same loop.
The name comes from Edsger Dijkstra, who described the problem using the three colours of the Dutch flag. The same three-way partition is used inside fast Quicksort implementations to handle many duplicate values.
Key takeaways#
- With only three distinct values you don't need to sort, you need to group.
- Three pointers split the array into a 0s zone, a 1s zone, an unknown zone and a 2s zone.
- 0 goes to
low, 2 goes tohigh, 1 stays; never advancemidafter a swap withhigh. - One pass,
O(n)time andO(1)space.