自己根据一个动画写的,简单来说就是个递归
先将数列不断二分长度,
当长度为1时,当前子序列有序,
否则将其二分为左,右两个子序列(长度为len/2,len-len/2)
然后将这两个子序列合并,完毕。
对了,那个c数组,最好是在外面开,否则在里面反复开数组会降低效率,增大sort时间
void Mergesort(int *a, int len)
{
int *b = a + len / 2;
int lenb = len - len / 2;
if (len / 2 > 1)
Mergesort(a, len / 2);
if (lenb > 1)
Mergesort(b, lenb);
int k, j;
k = j = 0;
for (int i = 0; i < len; i++)
{
if(j<len/2&&k<lenb)
{
if(a[j]<b[k])
c[i]=a[j++];
else
c[i]=b[k++];
}
else
{
if(j<len/2)
c[i]=a[j++];
else
c[i]=b[k++];
}
}
for (int i = 0; i < len; i++)
a[i] = c[i];
}
嗨呀,看了别人的代码,感觉改成while循环好清晰啊
于是去改了一个
void Mergesort(int *a, int len)
{
int *b = a + len / 2;
int lenb = len - len / 2;
if (len / 2 > 1)
Mergesort(a, len / 2);
if (lenb > 1)
Mergesort(b, lenb);
int k, j, i;
k = j = i = 0;
while(j<len/2 && k<lenb)
{
if(a[j]<b[k])
c[i++]=a[j++];
else
c[i++]=b[k++];
}
while(j<len/2)
c[i++]=a[j++];
while(k<lenb)
c[i++]=b[k++];
for (int i = 0; i < len; i++)
a[i] = c[i];
}
非递归归并排序
/*
author:revolIA
submit:;
*/
#include<bits/stdc++.h>
//#pragma GCC optimize(3)
using namespace std;
typedef long long ll;
const int maxn = 1e6+7;
int A[maxn],Tmp[maxn];
int n;
void MergeSort(int n){
for(int i=1;i<=n;i<<=1){
for(int j=1;j<=n;j += i<<1){
int l = j,r = j+i;
int L = j+i-1,R = min(j+i+i-1,n);
int pos = j;
while(l<=L&&r<=R){
if(A[l]<A[r]){
Tmp[pos++] = A[l++];
}else{
Tmp[pos++] = A[r++];
}
}
while(l<=L)Tmp[pos++] = A[l++];
while(r<=R)Tmp[pos++] = A[r++];
for(int k=j;k<=R;k++)A[k] = Tmp[k];
}
}
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&A[i]);
}
MergeSort(n);
for(int i=1;i<=n;i++){
printf("%d%c",A[i],i==n?'\n':' ');
}
return 0;
}