Merge two sorted arrays into the same array

Description of the problem: Let the subarrays a[0:k] and a[k+1:n-1] have been sorted (0<=k<=n-1). Try to design a combination of these two subarrays for sorting Algorithm for an ordered array a[0:n-1]. The computation time required for the algorithm in the worst case is O(n), and only O(1) auxiliary space is used. #include <stdio.h>

void DisplayArray(int *pArray, int nLen)
{
    for (int i = 0; i < nLen; ++i)
    {
        printf("array[%d] = %d\n", i, pArray[i]);
    }
}

// pArray1 and pArray2 are already sorted arrays, and they are required to be merged into pArray in order.
// The sorted array will not have duplicate elements
void MergeArray(int *pArray1, int nLen1, int *pArray2, int nLen2 , int *pArray)
{
    int i, j, n;

    i = j = n = 0;
    while (i < nLen1 && j < nLen2) // loop until the elements of an array are copied
    {
        if (pArray1[i] < pArray2[j]) // copy array1 elements
        {
            pArray[n++] = pArray1[i++];
        }
        else if (pArray1[i] > pArray2[j]) // copy elements of array2
        {
            pArray[n++] = pArray2[j++];                      
        }
        else // equal elements copy
        {
            pArray[n++] = pArray2[j++];                      
            ++i;
        }
    }

    if (i == nLen1) // copy elements of array2 if array1 has already been copied
    {
        while (j < nLen2)
            pArray[n++] = pArray2[j++];
    }
    else // copy array1 if array2 has already been copied Elements of
    {
        while (i < nLen1)
            pArray[n++] = pArray1[i++];
    }
}

int main()
{      
    int array1[] = {1, 4, 5, 7};
    int array2[] = {2, 3, 6, 8};
    int array3[8];
    MergeArray(array1, 4, array2, 4, array3);
    printf("Merge Array:\n");
    DisplayArray(array3, 8);

    return 1;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326919654&siteId=291194637