分析:從尾到頭比較A1和A2的數字,並把較大的數字復制到合適的位置。
1 #include <stdio.h> 2 #include "stdafx.h" 3 4 void DisplayArray(int* pArray, int nLength) 5 { 6 for(int i = 0 ; i < nLength; ++i) 7 printf("%d\t", pArray[i]); 8 printf("\n"); 9 } 10 11 int *MergeArray(int* pArray1, int nLength1, int* pArray2, int nLength2, int* pArray3) 12 { 13 if(pArray1 == NULL || pArray2 == NULL) 14 return NULL; 15 16 int k = nLength1 + nLength2 -1; 17 int i = nLength1 - 1; 18 int j = nLength2 - 1; 19 20 //先將array1復制到array3前面 21 for(int n = 0 ; n <= i; n ++) 22 pArray3[n] = pArray1[n]; 23 24 25 //從後往前比較array1和array2 26 while(i >= 0 && j >=0) 27 { 28 if(pArray1[i] > pArray2[j]) 29 pArray3[k --] = pArray1[i --]; 30 else 31 pArray3[k--] = pArray2[j--]; 32 } 33 while(j >= 0) 34 pArray3[k --] = pArray2[j --]; 35 36 return pArray3; 37 } 38 39 int main() 40 { 41 int array1[] = {1,4,5,7}; 42 int length1 = sizeof(array1)/sizeof(int); 43 printf("array1 is: "); 44 DisplayArray(array1, length1); 45 46 int array2[] = {2,3,6,8}; 47 int length2 = sizeof(array2)/sizeof(int); 48 printf("array2 is: "); 49 DisplayArray(array2, length2); 50 51 int length3= length1 + length2; 52 int array3[length3]; 53 54 int *pArray3 = MergeArray(array1,length1,array2,length2,array3); 55 printf("Merge Array: \n"); 56 DisplayArray(pArray3, length3); 57 58 return 0; 59 }