c++两数组合并算法

#include <iostream>

#define MAXSIZE 100

using namespace std;

int combine(int a[],int b[],int c[],int n,int m)

{

    int i=0,j=0,k=0;

    while(i<n&&j<m)

    {

        if(a[i]<b[j])

        {

            c[k++]=a[i++];

        }

        else

        {

            c[k++]=b[j++];

        }

    }

    if(i!=n)//i不等于n说明数组a还有没复制完的元素

    {

        for(;i<n;i++)c[k++]=a[i];

    }

    else if(j!=m)//同理j不等于m说明b还有没复制完的元素

    {

        for(;j<m;j++)c[k++]=b[j];

    }

}

int main()

{

    int arr1[MAXSIZE]={3,5,38,42,45};

    int arr2[MAXSIZE]={4,8,32,33,41,42,44,88};

    int arr3[MAXSIZE];

    combine(arr1,arr2,arr3,5,8);

    cout<<"数组1:";

    for(int i=0;i<5;i++)cout<<arr1[i]<<" ";

    cout<<" 数组2:";

    for(int j=0;j<8;j++)cout<<arr2[j]<<" ";

    cout<<" 两数组合并后:";

    for(int i=0;i<13;i++)

    {

        cout<<arr3[i]<<" ";

    }

    return 0;

}

运行结果:

原文地址:https://www.cnblogs.com/linruier/p/7521161.html