给定0,1,2组成的数组,把0,1,2按顺序排列,空间复杂度O(1),时间复杂度O(n)

package threecolor;


class Sort{

public int[] sort(int[] data) {
int l=0;
int r=data.length-1;
int i=0;
int t=0;
while(i!=r) {
if(data[i]==0) {
t=data[l];
data[l]=data[i];
data[i]=t;
l++;
}
if(data[i]==2) {
t=data[r];
data[r]=data[i];
data[i]=t;
r--;
i--;
}
i++;
}
return data;
}
}
public class ThreeColor {

public static void main(String[] args) {
int[] data=new int[] {1,0,1,2,2,0,1,1,2,0,2};
Sort s=new Sort();
data=s.sort(data);
for(int o:data) {
System.out.println(o);
}
}

}

posted @ 2018-05-04 16:12  特仑苏灬  阅读(396)  评论(0编辑  收藏  举报