堆排序

#include<algorithm>
#include<cstdio>
#include<iostream>
using namespace std;
int heap_size=0;
int heap[100001];


void put(int d)         //heap[1]为堆顶
{
    int now,next;
    heap[++heap_size]=d;
    now=heap_size;
    while(now>1)
    {
        next=now>>1;//取父节点相当于now/2 
        if(heap[now]>=heap[next])
         break;
        swap(heap[now],heap[next]);
        now=next; 
    }
}


int get()                //heap[1]为堆顶
{
    int now=1,next,res=heap[1];
    heap[1]=heap[heap_size--];//弹出首元素,用尾元素补上 
    while(now*2<=heap_size)
    {
        next=now*2;//左孩子 
        if(next < heap_size && heap[next + 1] < heap[next]) next++;
        if(heap[now] <= heap[next]) 
           break;
        swap(heap[now], heap[next]);
        now=next;
    }
    return res;
}
int main()
{
    int q;
    cin>>q;
    for(int i=1;i<=q;i++)
    {
        cin>>heap[i];
        put(heap[i]);
    }    
    for(int i=1;i<=q;i++)
    {
        cout<<get()<<" ";
    }
    return 0; 
}
原文地址:https://www.cnblogs.com/sssy/p/6651646.html