• 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--; } }
  • 相关阅读:
    PLSQL表
    CentOS服务器下JavaEE环境搭建指南(远程桌面+JDK+Tomcat+MySQL)
    数据分析业务调研
    Apache -poi
    Python入门经典
    高性能Linux服务器构建实战:运维监控、性能调优与集群应用
    新编 中文版CorelDRAW入门与提高
    早该这样学!Photoshop比你想的简单
    跟老男孩学Linux运维:MySQL入门与提高实践
    SQL查询的艺术
  • 原文地址:https://www.cnblogs.com/infoo/p/7603659.html
Copyright © 2020-2023  润新知