堆排序【模板】
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; }