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

    #include<iostream>
    #include<cstdio>
    
    using namespace std;
    int n,t,a;
    int heap[500010];
    
    void heap_up(int now)
    {
        if(now<=1) return;
        int top=now>>1;
        if(heap[now]<heap[top])
         {
             swap(heap[now],heap[top]);
                heap_up(top);
         }
    }
    
    void heap_down(int now)
    {
        if(now>n) return;
        int lc,rc,next=now;
          bool blc,brc;
        if((now << 1)<=n) blc=true,lc=heap[now << 1];
        else blc=false;
        if((now << 1 | 1)<=n) brc=true,rc=heap[now << 1 | 1];
        else brc=false;
        if(blc)
        {
            if(heap[next]>lc)
              next=now<<1;
        }
        if(brc)
        {
            if(heap[next]>rc)
              next=now << 1 | 1;
        }
        if(next!=now)
        {
            swap(heap[next],heap[now]);
              heap_down(next);
        }
    }
    
    void heap_pop()
    {
        heap[1]=heap[n];
        n--;
        heap_down(1);
    }
    
    void make_heap(int x)
    {
        t++;
        heap[t]=x;
        heap_up(t);
    }
    
    int main()
    {
        scanf("%d",&n);
        int m=n;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a);
            make_heap(a);
        }
        for(int i=1;i<=m;i++)
        {
            printf("%d ",heap[1]);
            heap_pop();
        }
        return 0;
    }
    折花枝,恨花枝,准拟花开人共卮,开时人去时。 怕相思,已相思,轮到相思没处辞,眉间露一丝。
  • 相关阅读:
    [12.19模拟赛]矩形|扫描线+set
    网 络
    数组(二维)
    数组
    02-线程的三种创建方式
    01-线程(概念篇)
    IO流-文件操作
    Serializable 可串行化接口
    PrintStream 类
    ObjectIntputStream / ObjectOutputStream 类
  • 原文地址:https://www.cnblogs.com/L-Memory/p/6241056.html
Copyright © 2011-2022 走看看