Algorithms
Dutch National Flag (3-Way Partition)
O(n) time — a single pass through the list, touching each item a constant number of times · O(1) extra space, since it sorts in place.
The idea, in plain English
Named after the Dutch flag's three horizontal stripes (red, white, blue), this trick sorts a list that only ever holds three distinct values — like 0s, 1s, and 2s — into their three neat groups in a single pass. Picture sorting a pile of laundry into three baskets, for whites, colors, and darks, by walking past each item exactly once, instead of picking it up over and over.
How it works
- 1Keep three markers: 'low', the boundary for 0s; 'mid', the item you are currently looking at; and 'high', the boundary for 2s.
- 2Look at the item at 'mid'. If it is a 0, swap it down to the 'low' boundary and move both low and mid forward. If it is a 1, it is already in the middle group, so just move mid forward.
- 3If it is a 2, swap it out to the 'high' boundary and pull high inward. Do not move mid yet, since the item swapped in from the high end still needs checking. Stop once mid passes high.
When you'd use it
Use it to sort data with only a small, fixed number of distinct categories — like sorting objects by three colors, classifying items as low, medium, or high, or as a splitting step inside quicksort when many items share the same value.
Common beginner mistakes
- Moving 'mid' forward after every swap, including swaps with 'high'. The item just pulled in from the high end has not been checked yet, so mid must stay put in that case.
- Using this approach on data with more than three distinct values. It is built specifically for exactly three categories, not general sorting.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Before: 2 0 2 1 1 0
Sorted: 0 0 1 1 2 2See it in motion
Three markers: low, mid, high. Press play to sort in one pass.
Not sure this is the right topic? See the learning paths → or where this leads →