#include<iostream>
#include<cstdlib>
#include <conio.h>
using namespace std;
template<class type>
void merge(type c[],type d[],int l,int m,int r)
{
int i,j,k;
k=i=l;
j=m+1;
while((i<=m)&&(j<=r))
{
if(c[i]<=c[j])
d[k++]=c[i++];
else
d[k++]=c[j++];
}
if(i>m)
for(int q=j;q<=r;q++)
d[k++]=c[q];
else
for(int q=i;q<=m;q++)
d[k++]=c[q];
};
template<class type>
void Mergersort(type a[],int left,int right,int n)
{
int i=0;
type *b=new type[n];
if(left<right)
{
i=(left+right)/2;
Mergersort(a,left,i,n);
Mergersort(a,i+1,right,n);
merge(a,b,left,i,right);
for(i=left;i<=right;i++)
a[i]=b[i];
}
}
int main()
{
int n=0,i=0,p=0,r=0;
cout<<"要排序的数的规模"<<endl;
cin>>n;
int *a=new int[n];
cout<<"输入要排序的数:"<<endl;
for(i=0;i<n;i++)cin>>a[i];
p=0;r=n-1;
Mergersort(a,p,r,n);
cout<<"输出排好的数:"<<endl;
for(i=0;i<n;i++)cout<<a[i]<<' ';
cout<<endl;
getch();
return 0;
}
合并排序
最新推荐文章于 2021-02-26 14:53:04 发布