C语言合并数组

来源:互联网 发布:淘宝外卖红包免费领取 编辑:程序博客网 时间:2024/09/21 06:19

有两个升序的数组,合成一个非降序的数组


#include <stdio.h>


int main(int argc,const char * argv[]) {

    // insert code here...


    int a[] = {1,5, 7,9, 12,15, 19};

    int b[] = {2,3, 6,8, 9};


    int aCount =sizeof(a) / sizeof(a[0]);

    int bCount =sizeof(b) / sizeof(b[0]);

    

    int c[aCount + bCount];

    int aPoint =0;

    int bPoint =0;

    

    for (int i =0; i < aCount + bCount; i++) {

        if (aPoint > aCount -1) {

            c[i] = b[bPoint];

            bPoint++;

        } elseif (bPoint > bCount - 1) {

            c[i] = a[aPoint];

            aPoint++;

        } elseif (aPoint < aCount && a[aPoint] < b[bPoint]) {

            c[i] = a[aPoint];

            aPoint++;

        } else {

            c[i] = b[bPoint];

            bPoint++;

        }

    }

    

    for (int i =0; i < sizeof(c) /sizeof(c[0]); i++) {

        printf("%d\t", c[i]);

    }


    

    return0;

}

0 0
原创粉丝点击