zoukankan      html  css  js  c++  java
  • stl_heap

    学习一下stl_heap 

             下面的算法是根据stl源码重新整合一下,是为了方便理解

             因为使用的迭代器,为了在给定的迭代器之间使用heap的一些方法,

             内部通常用disHole来确定某个节点 dishole 是指与first距离,可取0 1 2 3 4.....

    inline void push_heap(int heap[], int first, int last)
    {
        //disHole 指 当前结点 到first的距离 因此距离 是从 0 1 2 3 .....
        int disHole = (last - first) - 1;
        int disHoleParent = (disHole - 1) / 2;
        int value = heap[first+disHole];
        while (disHole> 0 && heap[first + disHoleParent] < value)
        {
            heap[first+disHole] = heap[first+disHoleParent];
            disHole = disHoleParent;
            disHoleParent = (disHole - 1) / 2;
        }
        heap[first + disHole] = value;
    }
    
    //调用此方法时 实际上将 最顶 元素 放到了最后
    //从上往下调整
    inline void pop_heap(int heap[], int first, int last)
    {
        int value = heap[last - 1];
        heap[last - 1] = heap[first];
        int disHole = first-first;
    
        int disSecondHoleChild = (disHole * 2 + 2);
        while (disSecondHoleChild < (last - first - 1))
        {
            if (heap[first + disSecondHoleChild] < heap[first + disSecondHoleChild - 1])
                disSecondHoleChild--;
            heap[first+disHole] = heap[first+disSecondHoleChild];
            disHole = disSecondHoleChild;
            disSecondHoleChild = (disHole * 2 + 2);
        }
        if (disSecondHoleChild == (last - first - 1))
        {
            heap[first + disHole] = heap[first + disSecondHoleChild - 1];
            disHole = disSecondHoleChild - 1;
        }
    
        heap[first+disHole] = value;
    //这一步,因为在while 循环中,并没有设置让当前大于子女节点时退时
    //所以插入后,使用push_head 进行向上调整
    //当然暂时不理解stl在设计时 为何在while中不进行判断 break push_heap(heap, first, disHole
    + 1); } //利用pop_heap 原理实现 排序 inline void sort_heap(int heap[],int first,int last) { while((last-first)>1) { pop_heap(heap, first, last--); } } //make_heap 将其调整为最大堆 inline void make_heap(int heap[],int first,int last) { if ((last - first) < 2)return; int dislen = last - first - 1; int disParent = (dislen - 1) / 2; while(true) { push_heap(heap, first, first + disParent + 1); if(disParent==0)return; disParent--; } }
  • 相关阅读:
    一图看懂host_only nat bridge拓扑结构
    Linux iptables原理--数据包流向
    linux iptables常用命令之配置生产环境iptables及优化
    linux service命令解析
    mysql 二进制日志后缀数字最大为多少
    mysql基于init-connect+binlog完成审计功能
    MySQL5.7(5.6)GTID环境下恢复从库思(qi)路(yin)方(ji)法(qiao)
    Centos6.5 python升级成2.7版本出现的一些问题解决方法
    python生成随机密码
    (原创)c++中的类型擦除
  • 原文地址:https://www.cnblogs.com/infoo/p/7603659.html
Copyright © 2011-2022 走看看