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.
11/2
Doing this in one pass is tricky, make a tiny mistake:
public class Solution {
private int RED = 0;
private int WHITE = 1;
private int BLUE = 2;
public void sortColors(int[] A) {
int len = A.length;
int r = 0, w = 0, b = len-1;
while(w <= b){ // err1: w<=b, think of the case [W,R]
if(A[w] == WHITE){
w++;
}else if(A[w] == RED){
swap(A,w,r);
r++;
w++;
}else if(A[w] == BLUE){
swap(A,w,b);
b--;
}
}
}
private void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}