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.

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

01 class Solution {
02 public:
03     void sortColors(int A[], int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int rcount=0;
07         int wcount=0;
08         for(int i=0;i<n;i++)
09         {
10             if(A[i]==0)
11                 rcount++;
12             if(A[i]==1)
13                 wcount++;
14         }
15         for(int i=0;i<rcount;i++)
16             A[i]=0;
17         for(int i=0;i<wcount;i++)
18             A[rcount+i]=1;
19         for(int i=rcount+wcount;i<n;i++)
20             A[i]=2;
21     }
22 };
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: Logo

You are commenting using your 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