/*
*Copyright (c) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称:Annpion.cpp
*作者:王耀鹏
*完成日期:2016年3月30日
*版本号:v1.0
*
*问题描述:归并排序
*输入描述:待排序数组
*输出描述:归并排序
*/
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
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 && 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; ++i,++k)
R[i]=R1[k];
}
void MergePass(RecType R[],int length,int n)
{
int i;
for(i=0; i+2*length-1<n; 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;
for(length=1; length<n; length*=2)
MergePass(R,length,n);
}
int main()
{
int i,n=10;
RecType R[MaxSize];
KeyType a[]= {6,8,7,9,0,1,3,2,4,5};
for (i=0; i<n; i++)
R[i].key=a[i];
printf("排序前:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
MergeSort(R,n);
printf("排序后:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
return 0;
}
运行结果: