merge两个数组,不用额外空间

方法:

1、把大数组的数往后移动n的位置,然后两数组从前往后合并

2、把指针定位在m+n处,两数组从后往前合并

/* Assuming -1 is filled for the places where element
   is not available */
#define NA -1

/* Function to move m elements at the end of array mPlusN[] */
void moveToEnd(int mPlusN[], int size)
{
    int i = 0, j = size - 1;
    for (i = size-1; i >= 0; i--)
        if (mPlusN[i] != NA)
        {
            mPlusN[j] = mPlusN[i];
            j--;
        }
}

/* Merges array N[] of size n into array mPlusN[]
   of size m+n*/
int merge(int mPlusN[], int N[], int m, int n)
{
    int i = n;  /* Current index of i/p part of mPlusN[]*/
    int j = 0; /* Current index of N[]*/
    int k = 0; /* Current index of of output mPlusN[]*/
    while (k < (m+n))
    {
        /* Take an element from mPlusN[] if
           a) value of the picked element is smaller and we have
              not reached end of it
           b) We have reached end of N[] */
        if ((i < (m+n) && mPlusN[i] <= N[j]) || (j == n))
        {
            mPlusN[k] = mPlusN[i];
            k++;
            i++;
        }
        else  // Otherwise take emenet from N[]
        {
            mPlusN[k] = N[j];
            k++;
            j++;
        }
    }
}


你可能感兴趣的:(merge两个数组,不用额外空间)