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
Last updated
Was this helpful?