有兩個排序數組A1和A2,內存在A1的末尾有足夠多的空余空間容納A2,實現一個函數,把A2插入到A1,並且是有序的。
分析:從尾到頭比較A1和A2的數字,並把較大的數字復制到合適的位置。
#include <stdio.h>
#include "stdafx.h"
void DisplayArray(int* pArray, int nLength)
{
for(int i = 0 ; i < nLength; ++i)
printf("%d\t", pArray[i]);
printf("\n");
}
int *MergeArray(int* pArray1, int nLength1, int* pArray2, int nLength2, int* pArray3)
{
if(pArray1 == NULL || pArray2 == NULL)
return NULL;
int k = nLength1 + nLength2 -1;
int i = nLength1 - 1;
int j = nLength2 - 1;
//先將array1復制到array3前面
for(int n = 0 ; n <= i; n ++)
pArray3[n] = pArray1[n];
//從後往前比較array1和array2
while(i >= 0 && j >=0)
{
if(pArray1[i] > pArray2[j])
pArray3[k --] = pArray1[i --];
else
pArray3[k--] = pArray2[j--];
}
while(j >= 0)
pArray3[k --] = pArray2[j --];
return pArray3;
}
int main()
{
int array1[] = {1,4,5,7};
int length1 = sizeof(array1)/sizeof(int);
printf("array1 is: ");
DisplayArray(array1, length1);
int array2[] = {2,3,6,8};
int length2 = sizeof(array2)/sizeof(int);
printf("array2 is: ");
DisplayArray(array2, length2);
int length3= length1 + length2;
int array3[length3];
int *pArray3 = MergeArray(array1,length1,array2,length2,array3);
printf("Merge Array: \n");
DisplayArray(pArray3, length3);
return 0;
}