Dutch National Flag
Arrays: lesson 11 of 14
Three values, three regions, one pass.
Lesson 11 of 14 · 5 min
Dutch National Flag
Step 1 of 7
Only three distinct values, so this is a partition, not a sort. Everything from i to high is unseen.
The Idea
With only three distinct values, sorting is really partitioning. Hold three walls: everything before low is the small value, everything after high is the large one, and the stretch from i to high is still unseen. Read the value at i and push it to the wall it belongs behind. A swap with high pulls in a value nobody has looked at, so the cursor must stay put for one more read.
Real-World Example
A returns desk sorting a bin into restock, inspect and scrap. Restock goes into the crate on the left, scrap into the crate on the right, inspect stays in the middle. Every item is handled exactly once.
The Code
def sort_colors(nums):
low, i, high = 0, 0, len(nums) - 1
while i <= high:
if nums[i] == 0: # belongs in the front block
nums[low], nums[i] = nums[i], nums[low]
low += 1
i += 1
elif nums[i] == 2: # belongs in the back block
nums[high], nums[i] = nums[i], nums[high]
high -= 1 # i stays: that value is unseen
else:
i += 1
return nums
print(sort_colors([2, 0, 1, 2, 0])) # [0, 0, 1, 2, 2]Your turn
Put the steps in the right order.
- Swap it with the value at high and pull high one step left
- Read the value under the cursor i
- Leave i where it is, because the value that arrived is unseen
- See that the value is the largest of the three
Mini quiz
1 / 3