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