如何将具有不同值的两个数组合并为一个数组?

osa*_*ama 3 c merge

假设您有一个数组a[]=1,2,4,6和一个第二个数组b[]=3,5,7.合并后的结果应该包含所有值,即c[]=1,2,3,4,5,6,7.合并应该在不使用函数的情况下完成<string.h>.

Bil*_*ter 7

我没有编译和测试以下代码,但我有理由相信.我假设两个输入数组已经排序.要做出这个通用目的还有很多工作要做,而不是只针对这个例子的解决方案.毫无疑问,我确定的两个阶段可以合并,但也许这将更难以阅读和验证;

void merge_example()
{
    int a[] = {1,2,4,6};
    int b[] = {3,5,7};
    int c[100];     // fixme - production code would need a robust way
                    //  to ensure c[] always big enough
    int nbr_a = sizeof(a)/sizeof(a[0]);
    int nbr_b = sizeof(b)/sizeof(b[0]);
    int i=0, j=0, k=0;

    // Phase 1) 2 input arrays not exhausted
    while( i<nbr_a && j<nbr_b )
    {
        if( a[i] <= b[j] )
            c[k++] = a[i++];
        else
            c[k++] = b[j++];
    }

    // Phase 2) 1 input array not exhausted
    while( i < nbr_a )
        c[k++] = a[i++];
    while( j < nbr_b )
        c[k++] = b[j++];
}
Run Code Online (Sandbox Code Playgroud)