兩個有序數組合併成一個大的有序陣列
public class use7 {
public static void main(String[] args) {
int[] a = { 3, 4, 7, 9 };
int[] b = { 1, 5, 6, 77 };
int[] result = MergeList(a, b);
for (int i : result) {
System.out.println(i);
}
}
public static int[] MergeList(int a[], int b[]) {
int result[];
// 定義一個新陣列,長度為兩個陣列長度之和
result = new int[a.length + b.length];
// i:a陣列下標 j:b陣列下標 k:新陣列下標
int i = 0, j = 0, k = 0;
// 按位迴圈比較兩個陣列,較小元素的放入新陣列,下標加一(注意,較大元素對應的下標不加一),直到某一個下標等於陣列長度時退出迴圈
while (i < a.length && j < b.length)
if (a[i] <= b[j]) {
result[k++] = a[i++];
System.out.print(result);
System.out.println();
} else {
result[k++] = b[j++];
}
/*
* 後面連個while迴圈是用來保證兩個陣列比較完之後剩下的一個數組裡的元素能順利傳入 *
* 此時較短陣列已經全部放入新陣列,較長陣列還有部分剩餘,最後將剩下的部分元素放入新陣列,大功告成
*/
while (i < a.length)
result[k++] = a[i++];
while (j < b.length)
result[k++] = b[j++];
return result;
}
}