Sort Colors

75 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.

Colors: 0, 1, 2

public void sortColors(int[] a) {
    if (a == null || a.length <=1) {
        return;
    }
    //       r   i     b
    // 0 0 0 1 1 ? ... ? 2 2 2
    int zero = 0, second = a.length - 1;
    for (int i=0; i <= second; i++){
        if (a[i] == 0) swap (a, zero++, i);
        else if (a[i] == 2) swap (a, second--, i--); // A[b] is unknown, i-- check again 
    }
}

private void swap(int[] a, int i, int j){
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}

Sort Colors 2

Colors: 1, 2, ...., k 1. loop k/2 times, sort 2 numbers at a time

public void sortColors2(int[] colors, int k) {
    int min = 1, max = k;

    for (int i=0; i < k; i+=2){   // loop k/2 times
        int left = 0, right = colors.length - 1;
        for (int j = 0; j <= right; j++){
            if (colors[j] == min) swap(colors, j, left++);
            else if (colors[j] == max) swap(colors, j--, right--);
        }
        min++;
        max--;
    }
}

private void swap(int[] a, int i, int j){
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}

Last updated