Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library’s sort function for this problem.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

C++:
01 void swap(int& a, int& b){
02     int tmp=a;
03     a=b;
04     b=tmp;
05 }
06 
07 void sortColors(int A[], int n) {
08      if((n==0)||(n==1))
09           return;
10      int a=0;
11      int b=n1;
12      while(a<=b){
13          while((A[a]==0)&&(a<b))
14               a++;
15          while((A[b]==2)&&(a<b))
16               b;
17          if(a>=b)
18               break;
19          bool flaga=false;
20          bool flagb=false;
21          for(int j=a;j<=b;j++){
22              if((A[j]==0)&&(flaga==false)){
23                   swap(A[a],A[j]);
24                   flaga=true;
25               }
26               if((A[j]==2)&&(flagb==false)){
27                   swap(A[j],A[b]);
28                   flagb=true;
29               }
30               if(flaga&&flagb)
31                  break;
32          }
33          if((flaga==false)&&(flagb==false))
34                  return;
35       }
36 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

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