Algorithms · Visualized
Sort Colors (Dutch Flag)
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
This problem sorts an array containing only three distinct values (commonly 0, 1, 2 — representing red, white, blue) in a single pass, using three pointers. Time: O(n) average, O(n) — always a single pass worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Sort Colors (Dutch National Flag)
SortingThis problem sorts an array containing only three distinct values (commonly 0, 1, 2 — representing red, white, blue) in a single pass, using three pointers. It's named after the Dutch flag because the sorted result naturally groups into three solid colour bands. It's a specialised, faster alternative to a general sort when you know there are only three possible values.
How Sort Colors (Dutch Flag) Works
- Set three pointers: 'low' at the start, 'mid' at the start, and 'high' at the end of the array.
- Look at the element at 'mid'.
- If it's 0, swap it with the element at 'low', then advance both 'low' and 'mid'.
- If it's 1, it's already in the right band, so just advance 'mid'.
- If it's 2, swap it with the element at 'high', then move 'high' backward (but keep 'mid' where it is, to re-check the swapped-in value).
- Continue until 'mid' passes 'high' — the array is now grouped into three sorted bands: 0s, then 1s, then 2s.
Sort Colors (Dutch Flag) Worked Example
Input: [2, 0, 2, 1, 1, 0]
low=0,mid=0,high=5. arr[mid]=2 → swap with high → [0,0,2,1,1,2], high=4. arr[mid]=0 → swap with low → [0,0,2,1,1,2], low=1,mid=1. arr[mid]=0 → swap with low → [0,0,2,1,1,2] (no visible change), low=2,mid=2. arr[mid]=2 → swap with high → [0,0,1,1,2,2], high=3. arr[mid]=1 → mid=3. arr[mid]=1→mid=4. mid>high, stop. Result: [0,0,1,1,2,2].
def sort_colors(a):
lo, mid, hi = 0, 0, len(a) - 1
while mid <= hi:
if a[mid] == 0:
a[lo], a[mid] = a[mid], a[lo]
lo += 1; mid += 1
elif a[mid] == 1:
mid += 1
else:
a[mid], a[hi] = a[hi], a[mid]
hi -= 1
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Sort Colors (Dutch Flag) Time & Space Complexity
When to Use Sort Colors (Dutch Flag)
- Sorting data with exactly three known categories in one linear pass (e.g. classifying items into low/medium/high).
- A classic interview question testing three-pointer partitioning technique.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.