Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c - How do I merge two arrays having different values into one array?

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>.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...