原题:
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.
题意:就是给只有0,1,2,的数组进行排序,让0在最前面,1在中间,2在最后面
代码和思路:
public class ThreeColor {
public int[] sortThreeColor(int[] A, int n) {
//0区
int left = -1;
//2区
int right = n;
//指针
int index = 0;
//当指针位置与2区重合的时候,结束
while(index<right){
//如果为0,就与0区右边第一个数字进行交换,然后0区向右移一个位置,指针下移一位
if(A[index]==0){
swap(A,++left,index++);
}
//如果是2,就与2区左边第一个数字进行交换,但是指针不动,继续考察换过来的数字
else if(A[index]==2){
swap(A,index,--right);
}
//如果是1,直接跳过
else index++;
}
}
private static void swap(int [] A,int index1,int index2){
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
}