#include <iostream> using namespace std; void Maxheap(int *a,int i,int heapSize)//最大数调整 { int left=i*2+1;//i的左节点 int right=i*2+2; int largest;//中间变量 if(left<heapSize&&a[left]>a[i]) { largest=left; } else { largest=i; } if(right<heapSize&&a[right]>a[largest]) { largest=right; } if(largest!=i) { swap(a[i],a[largest]); Maxheap(a,largest,heapSize); } } void Maxheapbuild(int *a,int n)//最大数建造 { for(int i=n/2-1;i>=0;i--) { Maxheap(a,i,n-1); } } void Heapsort(int *a,int n)//堆排序 { Maxheapbuild(a,n); for(int i=n-1;i>0;i--) { swap(a[0],a[i]); Maxheap(a,0,i); } } int main() { int n=5; int a[10]; cout<<"Input Num"<<endl; for(int i=0;i<n;i++) { cin>>a[i]; } Heapsort(a,n); for(int j=0;j<n;j++) { cout<<a[j]<<" "; } return 0; }
时间: 2024-12-27 21:37:12