Tuesday, January 20, 2015

Sort Colors

Q:
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.

T:
Keep two pointers. One points to the last index where red should occur. One points to the first index where blue should occur. Traverse the array, when meeting red, swap it with the first pointer, when meeting blue, swap it with the second pointer. Increase or decrease the pointers when needed.

A:


class Solution {
public:
    void sortColors(int A[], int n) {
        int red = 0;
        int blue = n-1;
        int i=red;
        while(i <= blue) {
            if(A[i]==0) {
                swap(A[i], A[red]);
                red++;
                i++;
                continue;
            }
            if(A[i]==2) {
                swap(A[i], A[blue]);
                blue--;
                continue;
            }
            i++;
        }
    }
};

No comments:

Post a Comment