題目描述
有兩個排序數組A1和A2,內存在A1的末尾有足夠多的空餘空間容納A2.實現一個函數,把A2中的所有數字插入到A1並且所有的數字是排序的。
編程思路
從尾到頭比較A1和A2中的數字,並把較大的數字複製到A1的合適位置。
程序代碼(Java語言)
package 合併兩個數組;
public class Test {
public static int[] mergeArray(int[] array1,int[] array2) {
if(array1 == null || array2 == null)
return null;
int i = array1.length-1;
int j = array2.length-1;
int k = array1.length + array2.length-1;
int[] temp = new int[array1.length + array2.length];
while(k >=0) {
if(i >=0 && j >=0) {
if(array1[i] > array2[j]) {
temp[k] = array1[i];
k--;
i--;
} else if(array1[i] < array2[j]) {
temp[k] = array2[j];
k--;
j--;
} else {
temp[k] = array2[j];
temp[k-1] = array2[i];
k = k-2;
i--;
j--;
}
} else if(i >= 0 && j < 0) {
temp[k--] = array1[i--];
} else if( i < 0 && j >= 0) {
temp[k--] = array2[j--];
}
}
return temp;
}
public static void main(String[] args) {
int[] array1 = {3,5,7,8,9};
int [] array2 = {2,4,6,8};
int [] temp = mergeArray(array1,array2);
for(int i = 0;i < temp.length; i++) {
System.out.println(temp[i]);
}
}
}