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.

class Solution {
public:
    int partition(int *A, int begin, int end){
        int x = A[begin];
        int i = begin;
        for(int j = begin + 1; j <= end; j++){
            if (A[j] <= x){
                i++;
                swap(A[j],A[i]);
            }
        }
        swap(A[begin],A[i]);
        return i;
    }
    void mysort(int *A, int begin, int end){
        if (begin >= end){
            return;
        }
        int pivot = partition(A,begin,end);
        mysort(A,begin,pivot - 1);
        mysort(A,pivot + 1, end);    
    }
    void sortColors(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return mysort(A,0,n-1);
    }
};

 

posted @ 2013-07-10 04:28  一只会思考的猪  阅读(231)  评论(0)    收藏  举报