归并排序总结
程序员文章站
2022-03-24 13:45:41
...
#include <bits/stdc++.h>
using namespace std;
int n,r[1000],r1[1000];
void merge_(int r[],int r1[],int low,int mid,int high)
{
int i,j,k;
i=low,j=mid+1,k=low;
while((i<=mid)&&(j<=high))
if(r[i]<=r[j])
r1[k++]=r[i++];
else r1[k++]=r[j++];
while(i<=mid) r1[k++]=r[i++];
while(j<=high) r1[k++]=r[j++];
}//合成
void mergepass(int r[],int r1[],int length)
{
int i,j;
i=0;
while(i+2*length-1<n){
merge_(r,r1,i,i+length-1,i+2*length-1);
i=i+2*length;
}
if(i+length-1<n-1)
merge_(r,r1,i,i+length-1,n-1);
else
for(j=i;j<n;j++) r1[j]=r[j];
}//两个两个的归并
void mergesort(int r[])
{
int length;
length=1;
while(length<n){
mergepass(r,r1,length);
length=2*length;
mergepass(r1,r,length);
length=2*length;
}
}//归并;
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>r[i];
mergesort(r);
for(int i=0;i<n;i++)
cout<<r[i]<<' ';
return 0;
}
个人感觉归并排序是快排的逆运算,优点是没有栈的,速度比快排快;