#include "iostream" using namespace std; int parent(int i){ return i/2; } int left(int i){ return 2*i; } int right(int i){ return 2*i+1; } int heapSize; void display(int A[],int size){ for(int i=1;i<=size;i++) cout<<A[i]<<" "; cout<<endl; } void maxHeapify(int A[],int i){ int l,r,largest,t; l=left(i); r=right(i); if(l<=heapSize&&A[l]>A[i]) largest=l; else largest=i; if(r<=heapSize&&A[r]>A[largest]) largest=r; if(largest!=i){ t=A[i]; A[i]=A[largest]; A[largest]=t; maxHeapify(A,largest); } } void buildMaxHeap(int A[],int size){ heapSize=size; for(int i=heapSize/2;i>0;i--){ maxHeapify(A,i); } } void heapSort(int A[],int size){ buildMaxHeap(A,size); for(int i=size;i>1;i--){ int t=A[1]; A[1]=A[heapSize]; A[heapSize]=t; heapSize--; maxHeapify(A,1); } } void main(){ int A[100]; int size; cout<<"输入数组的个数"<<endl; cin>>size; cout<<"输入"<<size<<"个数"<<endl; for(int i=1;i<=size;i++) cin>>A[i]; display(A,size); heapSort(A,size); display(A,size); getchar(); getchar(); }