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.

click to show follow up.

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?

 
思路: 分析把0,1,2分为三份,仅需要两个挡板,则然后把符合要求的红色放在第一个挡板位置,此时索引增加1(由于交换过来的number已经判断过了);
而当符合要求的蓝色放在从后向前的挡板后时,则由于交换过来的数还没有判定,所需要索引不变; 画图应该会更直观。
 
r1,r2  |  w1,w2,... | b1,b2,b3...
 
JAVA代码:
  1. private void swap(int[] A,int a,int b) {
  2. int tmp = A[a];
  3. A[a] = A[b];
  4. A[b] = tmp;
  5. }
  6. public void sortColors(int[] A) {
  7. int len = A.length;
  8. int r=-1;
  9. int b=len;
  10. if(len==0) return;
  11. for(int i=0;i<b;i++) { // 后面的界值为b,b之后都已经排序好了
  12. if(A[i] == 0) {
  13. r++;
  14. swap(A,r,i);
  15. } else if(A[i] == 2) {
  16. b--;
  17. if(i==b) continue; //注意消除循环
  18. swap(A,i,b);
  19. i--;  // 注意修订索引 i
  20. }
  21. }

}

 

C++代码: 更加直观一些

  1. enum {RED,WHITE,BLUE};
  2. void sortColors(int A[], int n) {
  3. if(A==NULL) return;
  4. int redindex = 0;
  5. int blueindex = n-1; //uncertain
  6. int index=0;
  7. while(index<=blueindex) { // equal to blueindex , not less than the blueindex
  8. if(A[index]==RED) {
  9. swap(A[index],A[redindex]);
  10. index++;
  11. redindex++;
  12. } else if(A[index]==BLUE) {
  13. swap(A[index],A[blueindex]);
  14. blueindex--;
  15. } else
  16. index++;
  17. }
  18. }
posted @ 2014-07-02 19:29  purejade  阅读(88)  评论(0)    收藏  举报