Bird
0
0
DSA Cprogramming~3 mins

Why Sort Colors Two Pointer Dutch Flag in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could sort three colors perfectly in just one quick pass?

The Scenario

Imagine you have a box of colored balls mixed together: red, white, and blue. You want to arrange them so all reds come first, then whites, then blues. Doing this by picking each ball and checking where to put it manually is tiring and slow.

The Problem

Manually sorting each ball means checking every ball multiple times and moving them around again and again. This wastes time and can cause mistakes, like putting a red ball in the blue section by accident.

The Solution

The two-pointer Dutch Flag method uses just a few pointers to sort the balls in one pass. It smartly swaps balls to their right places without extra space or repeated checks, making sorting fast and simple.

Before vs After
Before
for (int i = 0; i < n; i++) {
  for (int j = i + 1; j < n; j++) {
    if (colors[j] < colors[i]) {
      int temp = colors[i];
      colors[i] = colors[j];
      colors[j] = temp;
    }
  }
}
After
int low = 0, mid = 0, high = n - 1;
while (mid <= high) {
  if (colors[mid] == 0) {
    int temp = colors[low];
    colors[low] = colors[mid];
    colors[mid] = temp;
    low++;
    mid++;
  } else if (colors[mid] == 1) {
    mid++;
  } else {
    int temp = colors[mid];
    colors[mid] = colors[high];
    colors[high] = temp;
    high--;
  }
}
What It Enables

This method lets you sort three groups quickly in one pass, saving time and effort in many real-world sorting tasks.

Real Life Example

Sorting laundry by color: whites, darks, and colors. Instead of sorting each piece multiple times, you can quickly separate them in one go using this method.

Key Takeaways

Manual sorting is slow and error-prone.

Two-pointer Dutch Flag sorts in one pass efficiently.

It uses swapping and pointers to organize colors fast.