日期:2014-05-18 浏览次数:20694 次
public class Test {
public static void main(String[] args) {
int n = 8;
int[] arr = new int[2 * n];
boolean[] bs = new boolean[2 * n];
Random ran = new Random();
for(int i = 0; i < n; i++) {
arr[i] = ran.nextInt(50) * 2 + 2;
}
for(int i = 2 * n - 1; i >= n; i--) {
arr[i] = ran.nextInt(50) * 2 + 1;
}
for(int i = 0, j = 2 * n; i < j; i++) {
int r = ran.nextInt(j);
if(i == r) {
continue;
}
arr[i] = arr[i] ^ arr[r];
arr[r] = arr[i] ^ arr[r];
arr[i] = arr[i] ^ arr[r];
}
for(int i = 0; i < n * 2; i++) {
System.out.format("%d, ", arr[i]);
}
System.out.print("\n----------------------------------------------------\n");
for(int i = 0, j = 2 * n; i < j; i++) {
if(i % 2 == 0) {
int k = i - 1;
while(++k < j - 1 && arr[k] % 2 != 0);
if(i != k) {
arr[i] = arr[i] ^ arr[k];
arr[k] = arr[i] ^ arr[k];
arr[i] = arr[i] ^ arr[k];
}
} else {
int k = i - 1;
while(++k < j - 1 && arr[k] % 2 == 0);
if(i != k) {
arr[i] = arr[i] ^ arr[k];
arr[k] = arr[i] ^ arr[k];
arr[i] = arr[i] ^ arr[k];
}
}
}
for(int i = 0; i < n * 2; i++) {
System.out.format("%d, ", arr[i]);
}
}
}
int[] arr = {1,3,4,6,8,3};
int [] temp = new int[arr.length];
int oddIndex=1;//奇数的index
int evenIndex=0;//偶数的index
for(int num:arr){
if(num%2==1){
temp[oddIndex]=num;
oddIndex +=2;
}else{
temp[evenIndex]=num;
evenIndex +=2;
}
}