递归
#include
#include
#include
#define maxn 10000
void Marge_sort(int ap[],int n);
void Divide(int ap[],int tmp[],int left,int right);
void Combine(int ap[],int tmp[],int l,int r,int rend);
int array[maxn];
//归并排序递归实现
void Marge_sort(int ap[],int n) //调整函数接口
{
int *tmp=(int *)malloc(sizeof(int)*n);
Divide(ap,tmp,0,n-1);
}
void Divide(int ap[],int tmp[],int left,int right) //先分解问题
{
int center;
if(left<right) //当元素不只有一个时,要先归后并
{
center=(left+right)/2;
Divide(ap,tmp,left,center);
Divide(ap,tmp,center+1,right);
Combine(ap,tmp,left,center+1,right);
}
}
void Combine(int ap[],int tmp[],int l,int r,int rend) //合并两个区间,线性表合并
{
int len=rend-l+1;
int lend=r-1;
int t=l;
while(l<=lend&&r<=rend)
{
if(ap[l]<=ap[r])tmp[t++]=ap[l++];
else tmp[t++]=ap[r++];
}
while(l<=lend)
{
tmp[t++]=ap[l++];
}
while(r<=rend)
{
tmp[t++]=ap[r++];
}
int i;
for(i=0;i<len;i++)ap[rend-i]=tmp[rend-i];
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)scanf("%d",&array[i]);
Marge_sort(array,n);
for(i=0;i<n;i++)printf("%d ",array[i]);
return 0;
}
非递归
#include
#include
#include
#define maxn 1000010
int array[maxn];
void combine(int ap[],int tmp[],int l,int r,int rend) //合并数组
{
int len=rend-l+1;
int lend=r-1;
int t=l;
while(l<=lend&&r<=rend)
{
if(ap[l]<=ap[r])tmp[t++]=ap[l++];
else tmp[t++]=ap[r++];
}
while(l<=lend)
{
tmp[t++]=ap[l++];
}
while(r<=rend)
{
tmp[t++]=ap[r++];
}
for(int i=0;i<len;i++)ap[rend-i]=tmp[rend-i];
}
void Combine_hand(int ap[],int tmp[],int n,int len) //对每一小段进行合并
{
int i,j;
for(i=0;i<=n-2*len;i+=2*len)
{
combine(ap,tmp,i,i+len,i+2*len-1);
}
if(i+len<n)combine(ap,tmp,i,i+len,n-1);
}
void Marge_sort(int ap[],int n) //len的长度慢慢增加
{
int *tmp=(int *)malloc(sizeof(int)*n);
int len=1;
while(len<n)
{
Combine_hand(ap,tmp,n,len);
len*=2;
printf("%d",array[0]);
for(int i=1;i<n;i++)printf(" %d",ap[i]);
printf("\n");
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)scanf("%d",&array[i]);
Marge_sort(array,n);
return 0;
}