# 合并有序数组

#include
#include “stdafx.h”

void DisplayArray(int* pArray, int nLength)
{
for(int i = 0 ; i < nLength; ++i)
printf(“%dt”, 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;
}