模擬實現堆

   堆分爲最小堆和最大堆。
   最小堆:堆頂的關鍵碼最小,每個節點的關鍵碼小於該節點的左右孩子結點,並且從根節點到每個節點的路徑上,關鍵碼依次遞增。
   最大堆:堆頂的關鍵碼最大,每個節點的關鍵碼大於該節點的左右孩子結點,並且從根節點到每個節點的路徑上,關鍵碼依次遞減。

將一棵二叉樹調整爲最小堆的方法:
1.比較左右孩子的關鍵碼大小,較小的用child標記
2.比較child和parent,如果child< parent,將它們交換
3.使用循環依次類推,調整至最小堆
同樣,將二叉樹調整爲最大堆方法類似。

所以,我們使用模板參數列表來控制大小堆,代碼如下:

#include<ostream>
using namespace std;
#include<vector>
#include<assert.h>

template<class T>
struct Less//小堆
{
    bool operator()(const T& left,const T& right)
    {
        return left<right;
    }   
};

template<class T>
struct Greater//大堆
{
    bool operator()(const T& left,const T& right)
    {
        return left>right;
    }   
};

template<class T,class Comper=Less<T>>
class Heap
{
public:
    Heap()
    {}
    Heap(const T array[],size_t size)
    {
        for(int idx=0;idx<size;++idx)
            _heap.push_back(array[idx]);
        int root=(_heap.size()-2)>>1;//找到倒數第一個非葉子結點·
        for(;root>=0;--root)
            _AdjustDown(root);
    }
    size_t Size()const
    {
        return _heap.size();
    }
    bool Empty()const
    {
        return _heap.empty();
    }
    const T& Top()const
    {
        return _heap[0];
    }
    void Insert(const T& data)
    {
        _heap.push_back(data);//直接插入到最後一個元素
        if(_heap.size()>1)//排成最小堆/最大堆
            _AdjustUp();
    }
    void Remove()//刪除堆頂
    {
        assert(!_heap.empty());
        std::swap(_heap[0],_heap[_heap.size()-1]);//將堆頂與最後一個結點交換位置
        _heap.pop_back();//最後一個結點出堆,即原來的堆頂
        if(_heap.size()>1)
        {
            int root=(_heap.size()-2)>>1;//找到倒數第一個非葉子結點·
            for(;root>=0;--root)
            _AdjustDown(root);//將整個樹排爲最小堆/最大堆
        }
    }
protected:
    void _AdjustDown(size_t parent)
    {
        size_t child=parent*2+1;
        size_t size=_heap.size();
        while(child<size)
        {
            Comper com;
            if(child+1<size && com(_heap[child+1],_heap[child]))//左孩子>右孩子,將右孩子標記爲孩子結點
                child+=1;
            if(Comper()(_heap[child],_heap[parent]))//孩子結點<小於雙親結點時,將兩結點交換位置
            {
                std::swap(_heap[child],_heap[parent]);
                parent=child;
                child=parent*2+1;
            }
            else
                return;
        }
    }
    void _AdjustUp()//向上排成最小/大堆
    {
        size_t child=_heap.size()-1;
        size_t parent=(child-1)>>1;
        while(child!=0)
        {
            if(Comper()(_heap[child],_heap[parent]))//孩子結點<小於雙親結點時,將兩結點交換位置
            {
                std::swap(_heap[child],_heap[parent]);
                child=parent;//向上排
                parent=(child-1)>>1;
            }
            else
                return;
        }
    }
private: 
    std::vector<T> _heap;
};

測試代碼:

void Test()
{
    int array[]={53,17,78,9,45,65,87,23};
    Heap<int,Greater<int>> hp(array,sizeof(array)/sizeof(array[0]));
    hp.Insert(4);
    hp.Remove();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章