Skip to content
StackDecode
Array techniquesAnimated

Dutch National Flag Algorithm

Partition an array into three groups in one pass with three pointers.

Time

O(n)

Extra space

O(1)

Use it for

Sorting 0/1/2 and 3-way partitioning.

How it works

  1. Sort an array of 0s, 1s and 2s in one pass without counting.
  2. Keep three pointers: low (end of the 0s), mid (the item being examined), high (start of the 2s).
  3. If a[mid] is 0, swap it with low and advance both. If 1, just advance mid. If 2, swap it with high and shrink high (do not advance mid: the swapped-in item is unchecked).
  4. Stop when mid passes high.

Watch it run

Loading animation…