/** * @author:(LiberHome) * @date:Created in 2019/2/27 16:49 * @description:實現二路歸併排序 * @version:$page03 */ /*已知有兩個遞增的有序數組,將它們合併爲一個有序數組*/ public class page03 { public static void main(String[] args) { int[] num00 = {1, 3, 77, 7866}; int[] num01 = {0, 0, 56, 344, 456, 24455}; int[] numResult; numResult = mergeArray(num00, num01); show(numResult); } private static void show(int[] numResult) { for (int i = 0; i < numResult.length; i++) { System.out.print(" " + numResult[i]); } } private static int[] mergeArray(int[] num0, int[] num1) { /*獲取結果數組長度*/ int size = num0.length + num1.length; /*新建一個結果數組*/ int[] answer = new int[size]; /*首先從2個數組的第一個元素開始比較,較小的進入結果數組*/ int i = 0; int j = 0; int k = 0; while (i < num0.length && j < num1.length) { int smaller = (num0[i] < num1[j] ? num0[i++] : num1[j++]); answer[k++] = smaller; } /*若是數組num0的全部元素都進入結果數組,數組num1未徹底進入*/ if (i == num0.length && j < num1.length) { /*數組num1剩下的元素所有直接接到結果數組後面*/ for (int m = j; m < num1.length; m++) { answer[k++] = num1[m]; } } /*若是數組num1的全部元素都進入結果數組,數組num0未徹底進入*/ if (j == num1.length && i < num0.length) { /*數組num0剩下的元素所有直接接到結果數組後面*/ for (int n = i; n < num0.length; n++) { answer[k++] = num0[n]; } } /*返回結果數組*/ return answer; } }