leetcode

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,1,1,2,0,1,2]

Apply two sum idea, use two pointers to track already moved red and blue indexes, if all moved to the right place, end the loop.

public void sortColors(int[] A) {
        if (A==null||A.length==0) {
            return;
        }

        int left = 0;
        int right = A.length-1;
        int index = 0;

        while(index<=right) {
            if (A[index]==0) {
                swap(A, index, left);
                left++;
                index++;
            } else if (A[index]==2) {
                swap(A, index, right);
                right--;
            } else {
                index++;
            }
        }
    }

    private void swap(int[] A, int i, int j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }