#include <iostream>
using namespace std;
void max_heapify(int a[],int i,int heap_size)
{
int l=2*i;
int r=2*i+1;
int largest=i;
if(l<=heap_size&&a[l]>a[i])
largest=l;
if(r<=heap_size&&a[r]>a[largest])
largest=r;
if(largest!=i)
{
int temp=a[i];
a[i]=a[largest];
a[largest]=temp;
max_heapify(a,largest,heap_size);
}
}
void build_max_heap(int a[],int heap_size)
{
for(int i= heap_size/2;i>=1;--i)
max_heapify(a,i,heap_size);
}
void heapsort(int a[],int length)
{
int heap_size=length;
build_max_heap(a,heap_size);
for(int i=length;i>=1;--i)
{
int temp=a[1];
a[1]=a[i];
a[i]=temp;
heap_size--;
max_heapify(a,1,heap_size);
}
}
int main()
{
int arr[]={-1,4,1,3,2,16,9,10,14,8,7};//下标为0添加一个元素,使数组从1开始
heapsort(arr,10);
int size=sizeof(arr)/sizeof(*arr);
for(int i=1;i<size;++i)
cout<<arr[i]<<' ';
cout<<endl;
system("pause");
return 0;
}