最近面試的時(shí)候遇到了一道算法題,兩個(gè)有序數(shù)組合并,要求新的數(shù)組也是有序的
此題比較簡(jiǎn)單务冕,主要是看數(shù)組元素進(jìn)行對(duì)比,插入的數(shù)組要夠大幻赚,還有要考慮可能純?cè)诘臄?shù)組不對(duì)稱(chēng)問(wèn)題禀忆,一組數(shù)據(jù)多的情況,下面上代碼
int * mergeArray(int * array1,int size1,int *array2,int size2) {
int index1 = 0;
int index2 = 0;
int index = 0;
int * resTemp = malloc(size1 + size2);
while (index1 < size1 && index2 < size2) {
if (array1[index1] < array2[index2]) {
resTemp[index++] = array1[index1++];
}
else
{
resTemp[index++] = array2[index2++];
}
}
if (index1 < size1) {
resTemp[index++] = array1[index1++];
}
if (index2 < size2) {
resTemp[index++] = array2[index2++];
}
return resTemp;
}