公共类 ArraysSortEvensFirst {
public static void main(String[] args) {
int[] arr = generateTestData();
System.out.println(Arrays.toString(arr));
ArraysSortEvensFirst test = new ArraysSortEvensFirst();
test.sortEvensFirst(arr);
}
private static int[] generateTestData() {
int[] arr = {1,3,5,6,9,2,4,5,7};
return arr;
}
public int[] sortEvensFirst(int[] arr) {
int end = arr.length;
int last = arr.length-1;
for(int i=0; i < arr.length; i++) {
// find odd elements, then move to even slots
if(arr[i]%2 > 0) {
int k = findEven(last, arr);
if(k > i) swap(arr, i, k);
last = k;
}
}
System.out.println(Arrays.toString(arr));
return arr;
}
public int findEven(int last, int[] arr) {
for(int k = last; k > 0; k--) {
if(arr[k]%2 == 0) {
return k;
}
}
return -1; // not found;
}
public void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
输出: [1, 3, 5, 6, 9, 2, 4, 5, 7] [4, 2, 6, 5, 9, 3, 1, 5, 7]