Sort Colors
75 Sort Colors
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
Last updated