Given an array of 0, 1, 2, arrange 0, 1, 2 in order, the space complexity is O(1), and the time complexity is 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);
}
}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325305625&siteId=291194637