Wednesday 27 March 2013

Given a character array as input. Array contains only three types of characters 'R', 'G' and 'B'. Sort the array such that all 'R's comes before 'G's and all 'G's comes before 'B's. Constraint: - No extra space allowed (except O(1) space like variables) and minimize the time complexity. You can only traverse the array once.


/*
 *   1. Initialise 2 variables Rpos = 0 and Bpos = size-1.
 *   2. Scan the array from left to right.
 *      For i=0 to i<size
 *      a. if Array[Rpos] == ‘R’ then Rpos++
 *      b. If Array[Bpos] == ‘B’ then Bpos--
 *      c. if Array[i] == ‘R’ and i > Rpos then swap Array[Rpos], Array[i] and Rpos++
 *      d. If Array[i] == ‘B’ and I < Bpos then swap Array[Bpos], Array[i] and Bpos—
 */

 int main()
 {
     char Array[]={'R','B','B','G','B','R','B','G','R','R','B','G','R','G','B','B','G','R','R','G'};
     int size = sizeof(Array)/sizeof(Array[0]);
     int Rpos=0, Bpos = size-1;
     for(int i=0; i < size ; i++)
     {
             if(Array[Rpos] == 'R' )
             {
                            Rpos++;
             }
             if(Array[Bpos] == 'B')
             {
                            Bpos--;
             }
             if(Array[i] == 'R' && i >Rpos)
                         swap(Array,Rpos++,i);
             if(Array[i] == 'B' && i < Bpos)
                         swap(Array,Bpos--,i);
     }
     display(Array,size);
     cout<<"\n";
     system("pause");
 }

1 comment:

  1. The code is wrong. It needs to be modified as follows :-

    int Rpos=0, Bpos = size-1;
    for(int i=0; i < size ;)
    {
    if(Array[Rpos] == 'R' )
    {
    Rpos++;
    }
    if(Array[Bpos] == 'B')
    {
    Bpos--;
    }
    if(Array[i] == 'R' && i >Rpos)
    swap(Array,Rpos++,i);
    else if(Array[i] == 'B' && i < Bpos)
    swap(Array,Bpos--,i);
    else
    i++;
    }

    ReplyDelete