//堆排序的最坏,平均,最好时间复杂度为O(nlogn),是不稳定的排序,空间复杂度是O(1).
#include <iostream>
using namespace std;
int A[9]={0,1,7,8,3,5,6,7,4};
int n=8;
void sift(int low,int high)
{
int i=low,j=2*i;
int t=A[i];
while(j<=high)
{
if(j<high&&A[j]<A[j+1])
j++;
if(A[j]>t)
{
A[i]=A[j];
i=j;
j=j*2;
}
else
break;
}
A[i]=t;
}
void heapsort()
{
int t;
for(int i=n/2;i>=1;i--) //构建初始堆
sift(i,n);
for(int i=n;i>1;i--) //每次取最大的数
{
t=A[1];
A[1]=A[i];
A[i]=t;
sift(1,i-1);
}
}
int main()
{
heapsort();
for(int i=1;i<9;i++)
cout<<A[i]<<" ";
return 0;
}