如何将具有不同值的两个数组合并为一个数组? [英] How do I merge two arrays having different values into one array?

查看:24
本文介绍了如何将具有不同值的两个数组合并为一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose you have one array a[]=1,2,4,6 and a second array b[]=3,5,7. The merged result should have all the values, i.e. c[]=1,2,3,4,5,6,7. The merge should be done without using functions from <string.h>.

推荐答案

我还没有编译和测试以下代码,但我相当有信心.我假设两个输入数组都已经排序.与仅针对此示例的解决方案相比,要实现此通用目的还有更多工作要做.毫无疑问,我确定的两个阶段可以合并,但可能更难阅读和验证;

I haven't compiled and tested the following code, but I am reasonably confident. I am assuming both input arrays are already sorted. There is more work to do to make this general purpose as opposed to a solution for this example only. No doubt the two phases I identify could be combined, but perhaps that would be harder to read and verify;

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++];
}

这篇关于如何将具有不同值的两个数组合并为一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆