MergeSort

来源:互联网 发布:·手机淘宝 编辑:程序博客网 时间:2024/06/04 18:39
#include<stdio.h>
#include<malloc.h>
#define MAXE 20
typedef int KeyType;
typedef char InfoType[10];
typedef struct{
        KeyType key;
InfoType data;
}RecType;
void Merge(RecType R[],int low,int mid,int high)
{
     RecType *R1;
int i=low,j=mid+1,k=0;
     R1=(RecType * )malloc((high-low+1)*sizeof(RecType));
while(i<mid+1&&j<high){
     if(R[i].key<R[j].key)
 R1[k++]=R[i++];
 else
 R1[k++]=R[j++];
}
while(i<mid)
     R1[k++]=R[i++];
while(j<high)
R1[k++]=R[j++];
for(k=0,i=low;i<=high;k++,i++)
R[i]=R1[i];
}
void MergePass(RecType R[],int length,int n)
{
     int i;
for(i=0;i<=n-2*length;i=i+2*length){
        Merge(R,i,i=length-1,i+2*length-1);
}
if(i+length-1<n){                //余下两个子表
Merge(R,i,i+length-1,n-1);
}
}
void MergeSort(RecType R[],int n){
     int length,i=1,k;
for(length=1;length<n;length=2*length){
    MergePass(R,length,n);
printf("第%d趟归并",i);
for(k=0;k<n;k++)
printf("%4d",R[k].key);
printf("\n");
}
}
0 0
原创粉丝点击