#include<stdio.h> #include<malloc.h> #define MAX 255 //自顶向下分治法 归并排序 int R[MAX]; void Merge(int low,int mid,int high) { int i=low,j=mid+1,p=0; int *R1; R1=(int *)malloc((high-low+1)*sizeof(int)); if(!R1) { puts("Insufficient memory avaliable!"); return; } while(i<=mid&&j<=high) { R1[p++]=(R[i]<=R[j])?R[i++]:R[j++]; } while(i<=mid) { R1[p++]=R[i++]; } while(j<=high) { R1[p++]=R[j++]; } for(p=0,i=low;i<high;p++,i++) { R[i]=R1[p]; } } void Merge_sort(int low,int high) { int mid; if(low<high) { mid=(high+low)/2; Merge_sort(low,mid); Merge_sort(mid+1,high); Merge(low,mid,high); } } int main() { //测试函数 printf("归并排序示例: "); int n,i; printf("Please input the number under %d ",MAX); scanf("%d",&n); if(n>MAX) { printf("The number is not right! "); return 0; } printf("Please input the array one by one: "); for(i=1;i<=n;i++) { scanf("%d",&R[i]); } printf("The array you input is: "); for(i=1;i<=n;i++) { printf("%d ",R[i]); } printf("The array after Heap_sort is: "); Merge_sort(1,n); for(i=1;i<=n;i++) { printf("%d ",R[i]); } return 0; }