Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You is not a suppose to use the library's sort function for this problem.
In short, the problem is given a sequence of three numbers containing 0,1,2, requiring that the sequence be re-integrated, the same elements placed in the adjacent position, the overall order is still 0,1,2. Requires that the sorting algorithm in the library function cannot be used.
The idea is very simple, do not rigidly adhere to the idea of sorting, first go through the array, statistics 0,1,2 three number of each occurrence of the frequency, and then rewrite the array.
void sortcolors (int A[], int n){int count[3] = { 0, 0, 0 }; IntI=0; for(I=0;I< n;I++){count[a[i]]++; }IntJ=0; for(I=0;I< count[0];I++){a[j++] = 0; } for(I=0;I< count[1];I++){a[j++] = 1; } for(I=0;I< count[2];I++){a[j++] = 2; }}
[Leetcode] Sort Colors