**
堆排序
**
#include<iostream>
using namespace std;
int h[1000],n;
void swap(int a,int b)
{
int t;
t=h[a];
h[a]=h[b];
h[b]=t;
return ;
}
void siftdown(int i)
{
int t,flag=0;
while(i*2<=n&&flag==0)
{
if(h[i]<h[2*i])
{
t=2*i;
}else{
t=i;
}
if(2*i+1<=n)
{
if(h[t]<h[2*i+1])
{
t=2*i+1;
}
}
if(t!=i)
{
swap(t,i);
i=t;
}else
flag=1;
}
return;
}
void creat(){
int i;
for(i=n/2;i>=1;i--)
{
siftdown(i);
}
return;
}
void heapsort(){
while(n>1)
{
swap(1,n);
n--;
siftdown(1);
}
return;
}
int main(){
int num;
cin>>num;
for(int i=1;i<=num;i++)
{
cin>>h[i];
}
n=num;
creat();
heapsort();
for(int i=1;i<=num;i++)
{
cout<<h[i]<<" ";
}
return 0;
}
输入:
14
99 5 36 7 22 17 46 12 2 19 25 28 1 32
输出:
1 2 5 7 12 17 19 22 25 28 36 46 92 99