交大OJ 1602 归并排序分解:合并两个已经排好序的数列

  1. Merge Sorted Array
    Description
    Given two sorted positive integer arrays num1 with length m and num2 with length n, merge num2 into num1 as one sorted array.
    Note:
    You may assume that num1 has enough space (size that is greater or equal to (m+n) to hold additional elements from num2.
    Initially, the number of elements in num1 and in num2 are m and n respectively.
    Your input should be two sorted arrays. Moreover, the output should be the merged sorted array.
    Every element from num1 and num2 should not exceed 10000.
    You need to consider all the circumstances, for example, one array is empty set.
    Sample Input
    3
    3
    1 5 7
    2 4 6
    Sample Output
    1 2 4 5 6 7

代码如下:

#include <iostream>

using namespace std;
int a[200000],b[200000],tmp[200000];
void merge(int *a,int *b,int m,int n)
{
    int s1=0,s2=0,i=0;
    while(s1<m&&s2<n)
    {
        if(a[s1]<=b[s2]) tmp[i++]=a[s1++];
        else
            tmp[i++]=b[s2++];
    }
     while(s1<m) tmp[i++]=a[s1++];
     while(s2<n) tmp[i++]=b[s2++];
}

int main()
{
    int m,n;
    cin>>m>>n;
    for(int i=0;i<m;i++) cin>>a[i];
    for(int i=0;i<n;i++) cin>>b[i];
    merge(a,b,m,n);
    for(int i=0;i<m+n;i++) cout<<tmp[i]<<' ';
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值