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.
定义指针start = -1,指针end = n;一次遍历,如果遇到0,交换给start,遇到2,交换给end,遇到1别管
public class Solution {
public void sortColors(int[] A) {
if(A.length <= 1) return;
int start = -1, end = A.length;
int p = 0;
while(p < A.length){
if(A[p] == 0){
if(p > start) swap(A, ++start, p);
else ++p;
}else if(A[p] == 2){
if(p < end) swap(A, p, --end);
else ++p;
}else ++p;
}
}
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}