Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

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.

Sumit KumarUpdated Oct 8, 20266 min readDSA
Sort an Array of 0s, 1s and 2s Without Sorting: Dutch National Flag Algorithm

"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.

Text
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 0 should be thrown to the left end.
  • A 2 should be thrown to the right end.
  • A 1 can 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:

Text
[ 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
  1. Start with low = 0, mid = 0, high = n - 1.
  2. While mid <= high, look at arr[mid]:
    • If it is 0: swap it with arr[low], then move both low and mid forward.
    • If it is 1: it is already in the middle zone, so just move mid forward.
    • If it is 2: swap it with arr[high] and move high back. Do not move mid, because the value that just arrived from high hasn't been checked yet.
  3. When mid passes high, the unknown region is empty and the array is sorted.
ApproachTimeExtra spacePasses
Library sortO(n log n)O(1) to O(n)Not allowed here
CountingO(n)O(1)2
Dutch National FlagO(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.

Animation: Dutch National Flag on 2 0 1 2 1 0 with low, mid and high pointers; 0s move to the left in blue, 2s to the right in red, ending sorted as 0 0 1 1 2 2
  1. arr[mid] = 2: swap with arr[high], giving [0, 0, 1, 2, 1, 2]. high moves to 4.
  2. arr[mid] = 0: swap with arr[low] (itself). low and mid move to 1.
  3. arr[mid] = 0: same again. low and mid move to 2.
  4. arr[mid] = 1: just move mid to 3.
  5. arr[mid] = 2: swap with arr[high], giving [0, 0, 1, 1, 2, 2]. high moves to 3.
  6. arr[mid] = 1: move mid to 4. Now mid > high, so we stop. Sorted in one pass.

Code#

Java#

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#

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++#

CPP
#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#

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 2

Python#

Python
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 2

Complexity analysis#

  • Time: O(n). Every step either moves mid forward or moves high back, so the unknown region shrinks by one each time. At most n steps.
  • Space: O(1). Three pointers, no matter how big the array is.

Edge cases and common mistakes#

  • Moving mid after swapping with high: this is the most common bug. The value that came from high could be a 0 or a 2 and must be checked first.
  • Using mid < high instead of mid <= high: the last unchecked element is skipped and the array can stay unsorted, for example [1, 0].
  • Why is it safe to move mid after swapping with low? Everything between low and mid - 1 is already a 1, so the value that comes back from low is a 1 (or the same 0 when low == mid).
  • Already sorted, all 0s, all 2s, or an empty array: all handled correctly by the same loop.
Note

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 to high, 1 stays; never advance mid after a swap with high.
  • One pass, O(n) time and O(1) space.