ALGORITHM PROBLEM : SORT AN ARRAY OF THREE COLOR BALLS

Approach:

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

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s