/*
建立的是一个小顶堆
*/
# include<cstdio>
# include<iostream>
# include<algorithm>
# include<cstring>
# include<string>
# include<cmath>
# include<queue>
# include<stack>
# include<set>
# include<map>
using namespace std;
# define inf 999999999
int h[101];//用来存放堆的数组
int n;//堆的大小
void _swap ( int x,int y )
{
int t;
t = h[x];
h[x] = h[y];
h[y] = t;
}
void siftdown( int i )
{
int t;
int flag = 0;//用flag来记录是否需要继续往下调整
while ( i * 2 <= n && flag == 0 )
{
if ( h[i] > h[i*2] )
{
t = 2*i;
}
else
{
t = i;
}
if ( 2*i+1 <= n )
{
if ( h[t] > h[2*i+1] )
{
t = 2*i+1;
}
}
if ( i!=t )
{
_swap( t,i );
i = t;
}
else
flag = 1;
}
}
void creat()
{//从最后一个非叶节点开始,逐步向上调整
for ( int i = n/2;i >= 1;i-- )
{
siftdown(i);
}
}
int deletemax()
{
int t;
t = h[1];
h[1] = h[n];
n--;
siftdown(1);
return t;
}
int main(void)
{
int num;
cin>>num;
for ( int i = 1;i <= num;i++ )
{
cin>>h[i];
}
n = num;
creat();
for ( int i = 1;i <= num;i++ )
{
cout<<deletemax()<<endl;
}
return 0;
}
建小顶堆以及推排序
最新推荐文章于 2022-11-03 10:38:31 发布