1. 程式人生 > >9.1-數組合並

9.1-數組合並

You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B.

Write a method to merge B into A in sorted order.

解法比較巧妙,需要從陣列後面往前遍歷,這樣的好處是新增元素後不會影響A原有的資料。

如果從前往後,新增元素會需要把A原有資料都往後移動一位。

#include <iostream>

using namespace std;
/*
You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B.
Write a method to merge B into A in sorted order.
*/
int * merge(int A[], int B[], int n, int m)
{
   int i=n-1, j=m-1, k=m+n-1;
   while(i>=0 && j>=0)
   {
       if(A[i]>B[j])
        A[k--]=A[i--];
        else
        A[k--]=B[j--];
   }
   while(j>=0)
    A[k--]=B[j--];

   return A;
}
int main()
{
    int A[7]={3,7,9}, n=3;
    int B[4]={2,5,6,8}, m=4;

    int *C=merge(A, B, n, m);
    for(int i=0;i<m+n;i++)
     cout<<C[i];

    return 0;
}