0
0
DSA Pythonprogramming~3 mins

Why Dutch National Flag Three Way Partition in DSA Python?

Choose your learning style9 modes available
The Big Idea

What if you could sort three groups in one quick sweep without extra effort?

The Scenario

Imagine you have a big box of mixed colored balls: red, white, and blue. You want to sort them so all reds come first, then whites, then blues. Doing this by picking each ball and placing it in the right spot by hand is tiring and slow.

The Problem

Sorting by hand means checking each ball multiple times, moving balls back and forth, and making mistakes. It takes a lot of time and effort, especially if the box is huge. You might lose track or mix colors again.

The Solution

The Dutch National Flag algorithm sorts the balls in just one pass. It smartly swaps balls to their correct places without extra space or repeated checks. This makes sorting fast, simple, and error-free.

Before vs After
Before
colors = ['red', 'blue', 'white', 'red', 'blue']
order = {'red': 0, 'white': 1, 'blue': 2}
# Manually check and move each ball multiple times
for i in range(len(colors)):
    for j in range(i+1, len(colors)):
        if order[colors[i]] > order[colors[j]]:
            colors[i], colors[j] = colors[j], colors[i]
After
colors = ['red', 'blue', 'white', 'red', 'blue']
low, mid, high = 0, 0, len(colors) - 1
while mid <= high:
    if colors[mid] == 'red':
        colors[low], colors[mid] = colors[mid], colors[low]
        low += 1
        mid += 1
    elif colors[mid] == 'white':
        mid += 1
    else:
        colors[mid], colors[high] = colors[high], colors[mid]
        high -= 1
What It Enables

This algorithm lets you sort three groups quickly and efficiently in just one pass, saving time and effort.

Real Life Example

Sorting laundry into whites, colors, and darks before washing to avoid color bleeding, done quickly without checking each piece multiple times.

Key Takeaways

Manual sorting is slow and error-prone.

Dutch National Flag algorithm sorts three groups in one pass.

It uses swapping and three pointers to organize efficiently.