Thursday, April 15, 2010

Dutch National Flag Problem

Dutch National Flag problem is posed as follows: Given an array with elements of 3 colors Red, Green and Blue, how would you sort them in Red, Green and Blue Order. One can definitelycount each elements and rewrite the array but another technique is to go through the array keeping 3 indexes, one representing Red (0), the other representing Green(1) and the third representing Blue(2). The variable are lo, mid and hi. lo represents first position where the value is not 0, hi represents first position from the end where value is not 2. mid represents past lo where the element is not 1. At anytime this invariant is maintained by swapping the elements in a loop. So when mid overtakes hi the algorithm terminates.



//solution 2 dutch flag problem
//as only 3 values exists it can also be solved using counting sort
void threecolors(int x[], int size){

int lo = 0, mid = 0, hi = size-1;

//move lo to a position where value is not 0
while ( lo < size && x[lo] ==0)
lo++;

//move hi to a position where value is not 2
while(hi >=0 && x[hi] == 2)
hi--;

//set mid to lo
mid = lo;
while (mid <= hi)
{

//swap with lo if mid points to 0
//swap with hi if mid points to 1
//increment mid if it points to 1
if ( x[mid] == 0) {
std::swap(x[lo],x[mid]);
lo++;mid++;
}
else if (x[mid] == 1)
mid++;
else
{

std::swap(x[mid],x[hi]);
hi--;
}
}
}

4 comments:

  1. Are you able to do it by only one scan? i.e. without knowing the size at the first place.

    ReplyDelete
  2. Lets say you had 3 distinct numbers and you wanted to sort them with a similar technique. How would develop that based on a similar technique

    ReplyDelete
  3. Yep, just remove the lines from 7 till 14

    ReplyDelete
  4. good job. well done :)

    ReplyDelete