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和2,0指针向右移,2指针向左移。
代码:
 1     void sortColors(int A[], int n) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int left = 0, right = n-1;
 5         while(A[left] == 0)
 6             left++;
 7         while(A[right] == 2)
 8             right--;
 9         int cur;
10         while(left < right){
11             for(cur = left; cur <= right; cur++){
12                 if(A[cur] == 0){
13                     A[cur] = A[left];
14                     A[left++] = 0;
15                     while(A[left] == 0)
16                         left++;
17                     break;
18                 }
19                 else if(A[cur] == 2){
20                     A[cur] = A[right];
21                     A[right--] = 2;
22                     while(A[right] == 2)
23                         right--;
24                     break;
25                 }
26             }
27             if(cur > right)
28                 break;
29         }
30     }

 

posted on 2013-11-06 19:59  waruzhi  阅读(134)  评论(0编辑  收藏  举报

导航