題目描述
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
public class ReOrderArray_13 {
//冒泡 O(n^2)
private static void reOrderArray1(int[] array) {
boolean tag = true;
for (int i=0; i<array.length && tag; i++) {
tag = false;
for (int j=0; j<array.length-1-i; j++) {
//左邊是偶數,右邊是奇數的情況交換
if ((array[j]&1)==0 && (array[j+1]&1)==1) {
tag = true;
int tmp =array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
}
//插入法O(n^2)
//與運算,只有都是1,結果纔是1,奇數&1=1,偶數&1=0
private static void reOrderArray2(int[] array) {
int j,key;
for (int i=1; i<array.length;i++) {
key = array[i];
if ((key&1)==0) continue;//如果是偶數跳過
j = i - 1;
//將奇數插在已遍歷的所有偶數前邊
while(j>=0 && (array[j]&1)==0) {
array[j+1] = array[j];
j--;
}
array[j+1] = key;
}
}
//歸併法,nlog(n)
private static void reOrderArray3(int[] array) {
mergeSort(array,0,array.length-1);
}
/**
* 歸併排序,合併排序
* @param arr 要排序的數組
* @param p 左邊索引
* @param r 右邊索引
*/
public static void mergeSort(int[] arr, int p, int r){
// 遞歸實現歸併排序
if(p<r){
int q = (p+r)/2;
mergeSort(arr, p, q);
mergeSort(arr, q+1, r);
merge(arr, p, q, r); //上面的合併算法
}
}
/**
* 合併
*/
public static void merge(int[] arr, int p, int q, int r){
// arr是數組,p,q,r爲下標。 p-q 和 q-r 爲已經排好序的兩個堆(不帶哨兵)
int n1 = q-p+1; // [p-q]左邊元素的個數,q元素歸左邊
int n2 = r-q; // (q-r]右邊元素個數
int[] L = new int[n1];
int[] R = new int[n2];
// arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
// src:要複製的數組(源數組)
// srcPos:複製源數組的起始位置
// dest:目標數組
// destPos:目標數組的下標位置
// length:要複製的長度
System.arraycopy(arr, p, L, 0, n1);
System.arraycopy(arr,q+1,R,0,n2);
for(int k=p,i=0,j=0; k<=r; k++){
if(i==n1)
arr[k] = R[j++]; // 左邊已經到頭了
else if(j==n2)
arr[k] = L[i++]; // 右邊已經到頭了
else if((L[i]&1)==1 || ((L[i]&1)==0 && (R[j]&1)==0))
arr[k] = L[i++]; // 左邊是奇數(或者左右都是偶數時) 的話左邊放入數組
else
arr[k] = R[j++]; // 否則右邊放入
}
}
public static void main(String[] args) {
int[] array = {1,3,42,34,54,7,12,4,8,9,24};
reOrderArray3(array);
for (int i = 0; i< array.length; i++) {
System.out.println(array[i]);
}
}
}