归并排序有两个步骤:一个是把每个分块先排好序,然后两两归并。最终实现归并排序,有两种思路,一个是递归实现归并但是意义并不是很大,因为这会额外占用较大内存。另一种是非递归实现归并。
我这里的代码只是说明归并的实现思想:
#include <set>
#include <vector>
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int n;
cin>>n;
int *a=new int[n];
int *b=new int[n];
int *c=new int[2*n];
for(int i=0;i<n;i++) //要先排好序
{
cin>>a[i];
}
for(int j=0;j<n;j++) //要先排好序
{
cin>>b[j];
}
int count_a=0,count_b=0;
int x=0;
while(count_a<=n-1&&count_b<=n-1)
{
if(a[count_a]<b[count_b])
{
c[x]=a[count_a];
x++;
count_a++;
}
else
{
c[x]=a[count_b];
x++;
count_b++;
}
}
while(count_a<=n-1)
{
c[x]=a[count_a];
count_a++;
x++;
}
while(count_b<=n-1)
{
c[x]=b[count_b];
x++;
count_b++;
}
for(int h=0;h<2*n;h++)
{
cout<<c[h]<<" ";
}
return 0;
}
对归并排序深入感兴趣的可以参考书目:Horowitz E,Sahni S.Fundamentals of Data Structures.