#include<stdio.h> #define MAX 255 //堆排序学习 int R[MAX]; void Heapify(int s,int m) { //调整堆 int j,temp; temp=R[s]; j=2*s; while(j<=m) { if(j<m&&R[j]>R[j+1]) j++; if(temp<R[j]) break; R[s]=R[j]; s=j; j=j*2; } R[s]=temp; } void BuildHeap(int n) { //初始建堆 int i; for(i=n/2;i>0;i--) Heapify(i,n); } void Heap_sort(int n) { //堆排序 int i; BuildHeap(n); for(i=n;i>1;i--) { R[0]=R[1];R[1]=R[i];R[i]=R[0]; Heapify(1,i-1); } } 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: "); Heap_sort(n); for(i=1;i<=n;i++) { printf("%d ",R[i]); } return 0; }