Sort Colors Visualization & Animation
Sorts an array of 0s, 1s, and 2s in one pass using Dijkstra's Dutch National Flag three-pointer algorithm.
## What is it?
Sort an array containing only 0s, 1s, and 2s in-place in a single pass without counting. Also known as the Dutch National Flag algorithm (by Dijkstra).
## How it works
- Three pointers: `low = 0` (boundary for 0s), `mid = 0` (current), `high = n-1` (boundary for 2s)
- While `mid <= high`:
- `arr[mid] == 0` → swap `arr[low]` and `arr[mid]`; advance `low++`, `mid++`
- `arr[mid] == 1` → already in place; advance `mid++`
- `arr[mid] == 2` → swap `arr[mid]` and `arr[high]`; `high--` (do NOT advance `mid` — the swapped element needs checking)
## When to use
- Sorting 3-valued arrays in one pass
- Generalized: k-way partition (extend with k pointers)
- Quicksort partition step (three-way partition for equal elements)
## Key Points
- O(n) time, O(1) space — single pass
- Do not increment `mid` after swapping with `high`, because the swapped element is unseen
- After the loop: [0..low-1] = 0s, [low..mid-1] = 1s, [high+1..n-1] = 2s
Category: algorithms
Difficulty: intermediate
- two-pointers
Time Complexity: O(n)
Space Complexity: O(1)
View Sort Colors VisualizationSort Colors
intermediateSorts an array of 0s, 1s, and 2s in one pass using Dijkstra's Dutch National Flag three-pointer algorithm.
low0
mid0
high11
0
[0]1
[1]1
[2]0
[3]1
[4]2
[5]1
[6]2
[7]0
[8]0
[9]0
[10]1
[11]50s51s22s
Initialising pointers…
Value 0
Value 1
Value 2
low pointer
mid pointer
high pointer
Init: low=0, mid=0, high=11. Array: [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
1 / 21