您的位置:首页 > 其它

堆排序【模板】

2017-04-08 08:08 363 查看
#include <algorithm>
#include <cstdio>

using namespace std;

int x,size,n;
int heap[1000005];

void push(int x)
{
int now,next;
heap[++size]=x;
now=size;
while(now>1)
{
next=now/2;
if(heap[next]<=heap[now]) return ;
swap(heap[next],heap[now]);
now=next;
}
}

int pop()
{
int now,next;
int ret=heap[1];
heap[1]=heap[size--];
now=1;
while(now*2<=size)
{
next=now*2;
if(next<size&&heap[next]>heap[next+1]) next++;
if(heap[now]<=heap[next]) return ret;
swap(heap[now],heap[next]);
now=next;
}
return ret;
}

int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
push(x);
}
for(int i=1;i<n;i++)
{
int ans=pop();
printf("%d ",ans);
}
printf("%d\n",pop());
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: