AlgoTales · Roadmap

Dutch National Flag

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The Dutch National Flag idea sorts items into three groups in a single walk, by pushing one group to the left end, another to the right end, and letting the third settle in the middle. It needs no extra list and is the heart of fast sorting.

Practical use cases

  • Web app: Sorting support tickets by priority. A helpdesk screen must show High priority tickets first, then Medium, then Low, across 50,000 open tickets. Instead of a general sort, one pass with three markers swaps each ticket into the right zone. The queue is grouped in a single sweep, and no second copy of the list is needed.
  • Web app: Grouping orders by status. An order dashboard wants Pending, Shipped and Delivered orders in three blocks, in memory, before drawing three tabs. Walking once and swapping each order to its block is quicker and lighter than sorting by text and building three new arrays from scratch.
  • System: Quicksort partitioning. Quicksort picks a pivot value and groups smaller, equal and larger items around it using this same three-way split. When a list has many repeated values, such as ratings from 1 to 5, the three-way version avoids repeated work and stays fast.

The story: Ribbons for Republic Day

For Republic Day, the school made a long ribbon string in the tricolour: saffron, white and green. But a careless helper had tied the ribbons in a jumble: green, saffron, white, green, saffron... Mrs. Sharma wanted them in order saffron first, then white, then green, and the parade started in ten minutes!

Aarav started to sort by counting every colour and rewriting the whole string. Zoya stopped him. "Use three fingers. One finger marks where the saffron section ends, one finger marks where the green section begins, and your main finger walks through the unchecked ribbons in the middle."

If the walking finger meets saffron, swap it to the saffron edge. If it meets green, swap it to the green edge. If it meets white, leave it alone. After one walk, everything was in order, and the parade began on time.

This is the Dutch National Flag problem (named after the Dutch tricolour), the classic way to sort an array that contains just three kinds of values in a single pass, without extra space. It is also the heart of the partition step inside quicksort.

How to spot this problem, and where you need it

You have items falling into just a few categories, like three priorities or statuses, and need them grouped together quickly without the cost and memory of a full sort.

Signs you need it

  • Items only have 2 or 3 possible values, such as 0, 1 and 2, red, white and blue, or low, medium and high.
  • The problem says sort in place, one pass, or without using the built-in sort or extra arrays.
  • You call sort or build three filtered arrays and merge them, on a very large list.

Where to use it in a project

  • Priority queues for support tickets, tasks and notifications that only have a handful of levels.
  • Partition steps inside sorting code, and bulk grouping of records by a small set of statuses before display.

The solution

Keep three markers: low for the end of the first group, mid for the item you are looking at, and high for the start of the last group. If the item at mid belongs to the first group, swap it with low and move both forward. If it belongs to the middle group, just move mid. If it belongs to the last group, swap it with high and move high back, without moving mid yet.

Payoff: Before: a full sort or three new arrays for 50,000 tickets. After: one in-place pass, each ticket looked at once.

Explain it like I am 8

Three kinds of marbles are mixed in a tray: red, white, green. You push the reds to the left end, the greens to the right end, and the whites naturally stay in the middle. One walk down the tray and you are done.

How it works, step by step

  1. Set low = 0, mid = 0, high = n - 1. Items before low are 0s, after high are 2s.
  2. While mid <= high, look at a[mid].
  3. If it is 0: swap with a[low], then low++ and mid++.
  4. If it is 1: it is in the right zone already, so just mid++.
  5. If it is 2: swap with a[high] and high--. Do not move mid, the item swapped in has not been checked yet.

The code in four languages

PHP

<?php
// Dutch National Flag: sort an array of 0s, 1s and 2s in one pass
function sortColors(array $a): array {
    $low = 0;
    $mid = 0;
    $high = count($a) - 1;
    while ($mid <= $high) {
        if ($a[$mid] === 0) {
            [$a[$low], $a[$mid]] = [$a[$mid], $a[$low]];    // send to the saffron zone
            $low++;
            $mid++;
        } elseif ($a[$mid] === 1) {
            $mid++;                                          // white: leave it
        } else {
            [$a[$mid], $a[$high]] = [$a[$high], $a[$mid]];  // send to the green zone
            $high--;                                         // mid stays: new item unchecked
        }
    }
    return $a;
}

echo implode(' ', sortColors([2, 0, 1, 2, 0, 1, 0, 2])) . PHP_EOL;   // 0 0 0 1 1 2 2 2

JavaScript

// Dutch National Flag: sort an array of 0s, 1s and 2s in one pass
function sortColors(a) {
  let low = 0;
  let mid = 0;
  let high = a.length - 1;
  while (mid <= high) {
    if (a[mid] === 0) {
      [a[low], a[mid]] = [a[mid], a[low]];    // send to the saffron zone
      low++;
      mid++;
    } else if (a[mid] === 1) {
      mid++;                                  // white: leave it
    } else {
      [a[mid], a[high]] = [a[high], a[mid]];  // send to the green zone
      high--;                                 // mid stays: new item unchecked
    }
  }
  return a;
}

console.log(sortColors([2, 0, 1, 2, 0, 1, 0, 2]).join(' '));   // 0 0 0 1 1 2 2 2

Java

import java.util.*;

public class Main {
    // Dutch National Flag: sort an array of 0s, 1s and 2s in one pass
    static int[] sortColors(int[] a) {
        int low = 0;
        int mid = 0;
        int high = a.length - 1;
        while (mid <= high) {
            if (a[mid] == 0) {
                swap(a, low, mid);     // send to the saffron zone
                low++;
                mid++;
            } else if (a[mid] == 1) {
                mid++;                 // white: leave it
            } else {
                swap(a, mid, high);    // send to the green zone
                high--;                // mid stays: new item unchecked
            }
        }
        return a;
    }

    static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(sortColors(new int[]{2, 0, 1, 2, 0, 1, 0, 2})));   // [0, 0, 0, 1, 1, 2, 2, 2]
    }
}

Go

package main

import "fmt"

// sortColors sorts a slice of 0s, 1s and 2s in one pass.
func sortColors(a []int) []int {
	low, mid, high := 0, 0, len(a)-1
	for mid <= high {
		if a[mid] == 0 {
			a[low], a[mid] = a[mid], a[low] // send to the saffron zone
			low++
			mid++
		} else if a[mid] == 1 {
			mid++ // white: leave it
		} else {
			a[mid], a[high] = a[high], a[mid] // send to the green zone
			high--                            // mid stays: new item unchecked
		}
	}
	return a
}

func main() {
	fmt.Println(sortColors([]int{2, 0, 1, 2, 0, 1, 0, 2})) // [0 0 0 1 1 2 2 2]
}

Time: O(n) · Extra space: O(1). Each step either moves mid forward or high backward, so the unchecked middle zone shrinks every time. No extra array.

Watch out for

  • Moving mid after swapping with high. The value that arrived from the right has not been examined yet.
  • Using mid < high instead of mid <= high, which leaves the last unchecked ribbon unsorted.
  • Sorting with a general sort when only three values exist. It works, but wastes the O(n) trick.

Quick check

  1. When mid sees a 2, what do you do?
    • Swap with low, move mid
    • Just move mid
    • Swap with high, move high back
  2. What does the zone between low and mid contain?
    • 1s (white)
    • Unchecked items
    • 0s only
  3. How many passes does the algorithm make over the array?
    • Three, one per colour
    • One
    • n