优先队列(二叉堆)

来源:互联网 发布:告白夫妇网络漫画 编辑:程序博客网 时间:2024/06/05 09:50

二叉堆的主要操作有deleteMin(),insert()和buildHeap()。deleteMin()和buildHeap()采用下滤,insert()采用上滤。

#include <vector>template <typename Comparable>class BinaryHeap{public:    explicit BinaryHeap(int capacity=100);    explicit BinaryHeap(const std::vector<Comparable> & items)    :array(items.size()+10),currentSize(items.size())    {        for(int i=0;i<items.size();++i)        {            array[i+1]=items[i];            bulidHeap();        }    }    bool isEmpty()const    {        return currentSize==0;    }    const Comparable & finMin()const    {        //if(isEmpty())            //throw UnderflowException{};        return array[1];    }    void insert(const Comparable & x)    {        if(currentSize==array.size()-1)            array.resize(array.size()*2);        int hole=++currentSize; //创建一个hole        Comparable copy=x;        array[0]=std::move(copy);        for(;x<array[hole/2];hole/=2)   //如果x小于父节点,则将父节点值放到hole上,然后将hole上移            array[hole]=std::move(array[hole/2]);        array[hole]=std::move(x);   //最后将x插入合适的位置    }    void insert(Comparable && x);    void deleteMin()    {       // if(isEmpty())            //throw UnderflowException{};        array[1]=std::move(array[currentSize--]);        percolateDown(1);    }    void deleteMin(Comparable & Minitem)    {        //if(isEmpty())            //throw UnderflowException{};        Minitem=std::move(array[1]);        array[1]=std::move(array[currentSize--]);        percolateDown(1);    }    void makeEmpty()    {        currentSize=0;    }private:    int currentSize;    std::vector<Comparable> array;    void bulidHeap()    {        for(int i=currentSize/2;i>0;--i)            percolateDown(i);    }    void percolateDown(int hole)    //下滤操作    {        int child;        Comparable tmp=std::move(array[hole]);  //相当于将最后一个元素插入到合适位置        for(;hole*2<=currentSize;hole=child)    //hole下移        {            child=hole*2;   //子节点            //在两个子节点中找到较小的那个,排除只有一个子节点的情况            if(child!=currentSize&&array[child+1]<array[child])                ++child;            if(array[child]<tmp)                array[hole]=std::move(array[child]);            else                break;        }        array[hole]=std::move(tmp);    }};
原创粉丝点击