建小顶堆以及推排序

来源:互联网 发布:智能交通 数据挖掘 编辑:程序博客网 时间:2024/06/11 14:05
/*    建立的是一个小顶堆*/# 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 999999999int 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;}

0 0
原创粉丝点击