zoukankan      html  css  js  c++  java
  • 堆排序

    #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; 
    }
  • 相关阅读:
    HDU 2081 手机短号
    HDU 2053 Switch Game
    HDU 2040 亲和数
    HDU 2070 Fibbonacci Number
    redis集群安装2
    redis集群1
    批量更新sql
    centos 6升级 GCC 到4.8
    排序4 -- 插入排序
    排序3--选择排序
  • 原文地址:https://www.cnblogs.com/sssy/p/6651646.html
Copyright © 2011-2022 走看看