Skip to content
BytePatterns

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]

Python

Your turn

Put the steps in the right order.

  1. Swap it with the value at high and pull high one step left
  2. Read the value under the cursor i
  3. Leave i where it is, because the value that arrived is unseen
  4. See that the value is the largest of the three

Mini quiz

1 / 3

Why does i not advance after a swap with high?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.