Dutch National Flag Problem
Given balls of three colors, say red white and blue randomly arranged, the aim is to arrange all the balls of same color together as in the flag using only the swap operation.
The algorithm is similar to the partition algorithm used in quicksort. We separate the array into three regions: <low, >=low && <high, >high.
void three_partition(int data[], int size, int low, int high)
{
int x = -1;
int y = size;
for(int i = 0;i<y;)
{
if(data[i]<low)
{
swap(data[i], data[++x]);
i++;
}
else if(data[i]>=high)
{
swap(data[i], data[–y]);
}
else
{
i++;
}
}
}
Lets give numbers corresponding to colors, say red = 0, white = 1 and blue = 2, pass low = 1 and high =2 in the function.
Btw: dutch national flag.