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.

题意:就是给包含0,1,2的数组排序。

要求只遍历序列一次

mid不应该从1开始,而需从0开始,这样才能防止A[0]=2

class Solution {
public:
    void swap(int* a,int i,int j){
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
    }
    void sortColors(int A[], int n) {
        if(A==NULL||n<=1) return;
        int l=0;
        int mid=0;
        int r=n-1;
        while(A[l]==0){++l;++mid;}
        while(A[r]==2) --r;
        while(mid<=r){
            if(A[mid]==1) ++mid;
            else if(A[mid]==2) {swap(A,mid,r);--r;}
            else if(A[mid]==0) {swap(A,mid,l);++l;++mid}
        }
    }
};

 

 
posted @ 2015-01-09 15:54  雄哼哼  阅读(147)  评论(0编辑  收藏  举报