面试题----合并两个有序数组

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void merge(int a[],int len1,int b[],int len2)
{
    if(len1 <= 0 || len2 <= 0)
        return;

    int *c = (int *)malloc(sizeof(int) * (len1 + len2));
    memset(c,0,sizeof(int) * (len1 + len2));

    int i = 0;
    int m = 0;
    int n = 0;

    while(m < len1 && n < len2)
    {
        if(a[m] < b[n])
        {
            c[i] = a[m];
            m++;
        }
        else
        {
            c[i] = b[n];
            n++;
        }
        i++;
    }
    if(m == len1)//说明是a先结束
    {
        for(;n < len2;n++)
        {
            c[i] = b[n];
            i++;
        }
    }
    else if(n == len2)//说明b先结束
    {
        for(;m < len1;m++)
        {
            c[i] = a[m];
            i++;
        }
    }
    printf("合并后的结果为:\n");
    int k = 0;
    for(;k < i;k++)
        printf("%d  ",c[k]);
    printf("\n");
    free(c);

}

int main()
{
    int a[] = {1,3,4,7,12,13,17,43,52,110};
    int b[] = {0,2,4,5,6,9,44};
    merge(a,10,b,7);
}

 

posted @ 2017-11-13 14:16  青儿哥哥  阅读(609)  评论(0编辑  收藏  举报