Friday, May 25, 2012

Algorithm Problem : Sort an Array of Three Color Balls

I have been practicing Algorithm problems for a while and thought it would be a good idea to post it for people with similar intrested. I will post new questions as often as I get time from my work schedule. Your feedback is welcome :)
---------------------------------------------------------------------------------------------------------

Q#1. Consider an Array of balls. A ball can be of one of the three colors Red/Green/Blue. Ask is to sort this array.
Follow up Question, Perform this operation in O (n) time.
Solution:
Analysis:
Let’s reduce some ambiguities from the problem.
n  Is there a weightage associated to colors of these balls?
No, consider all balls to have equal weightage.
n  By sorting is there a particular ordering required of these colors?
Yes, Red followed by Green and then Blue
We can consider the array of balls as a char array of length n with characters R, G and B. The array has length ‘N’
Unsorted array can be depicted as:

G

R

B

R

G

R

B

G

G

B
Sorted array can be depicted as:

R

R

R

G

G

G

G

B

B

B
Approach:
Being specific to this problem, we should try to arrange Red color at the start of the array, Blues at the rear of the array, Green’s will automatically be arranged in between.
Pseudo Code:
DECLARE CtrRed=0, CtrBlue=N-1                                 // Initiate Red and Blue counter index
FOR I = 0 TO N-1                                               // Control Loop
IF CtrRed < CtrBlue                          // Red Index cannot be greater than Blue Index
IF Array[I] = ‘R’ THEN SWAP(Array[I], Array[CtrRed++])                  //Swap Red Color
IF Array[I] = ‘B’ THEN SWAP(Array[I], Array[CtrBlue--])                  //Swap Blue Color
I = I - 1                //Decrement the counter when Blue Ball is found, since swapped color may be Red
C# Code:
       public static char[] SortColors(char[] InputArray)
        {
            //Error Handler
            if (InputArray == null || InputArray.Length == 0)
                throw new Exception("Input Array Is Null or Empty");
            //Variable Declaration and Initialization
            int ctrRed = 0, ctrBlue = InputArray.Length - 1;
            for (int i = 0; i < ctrBlue; i++)
            {
                if (ctrRed < ctrBlue)
                {
                    if (InputArray[i] == 'R')
                    {
                        Swap(ref InputArray[i], ref InputArray[ctrRed++]);
                    }
                    else if (InputArray[i] == 'B')
                    {
                        Swap(ref InputArray[i], ref InputArray[ctrBlue--]);  
                        i--; 
                    }
                }
            }
            return InputArray;
        }
        public static void Swap(ref T InputA, ref T InputB)
        {
            T temp = InputA;
            InputA = InputB;
            InputB = temp;
        }

Time complexity for this algorithm is O(n)

4 comments:

Manisha said...

Very efficient algorithm..

Manisha said...

Very efficient algorithm..

bee said...

thnks.....

Unknown said...

https://coderpad.io/PG6YQCT4