算法导论—堆

来源:互联网 发布:日语培训 知乎 编辑:程序博客网 时间:2024/04/28 04:43
<pre name="code" class="cpp">#include <vector>#include <iostream>using namespace std;class UnderflowException { };template<typename Comparable>class BinaryHeap{public:explicit BinaryHeap(int capacity=100):array(capacity+1),currentSize(0){ }explicit BinaryHeap(const vector<Comparable> &items):array(items.size()+10),currentSize(items.size()){for(int i=0;i<items.size();++i)array[i+1]=items[i];buildMaxHeap();}bool isEmpty() const{return currentSize==0;}int currSize() const{return currentSize;}void  print(){for(int i=1;i<=currentSize;++i)cout<<array[i]<<" ";cout<<endl;}const Comparable& findMax() const{if (isEmpty())throw UnderflowException{ };return array[1];}//Increase the value in position i to keyint increaseKey(int i,const Comparable &key){if (key<array[i]){cout<<"new key is smaller than current key,can not change"<<endl;return -1;}array[i]=key;while(i>1&&array[i/2]<array[i]){std::swap(array[i/2],array[i]);i=i/2;}return 0;}//Insert the x into the heapvoid insert(const Comparable &x){if (currentSize==array.size()-1)array.resize(array.size()*2);int hole=++currentSize;array[hole]=INT_MIN;increaseKey(hole,x);}/* *Remove the maximum item and return it *Throws Underflow if empty */ int deleteMax() { if(isEmpty()) throw UnderflowException{ }; int tmp=array[1]; std::swap(array[1],array[currentSize--]); maxHeapIfy(1); return tmp; } /**  *heapSort  */  void heapSort(vector<Comparable> &vec)  {  while(currentSize)  {  int tmp=deleteMax();  vec.push_back(tmp);  }  }private:int currentSize;  //number of elements in heapvector<Comparable> array;/** *Establish heap order property from an arbitrary *arrangement of items.Runs in nlgn time. */void buildMaxHeap(){for(int i=currentSize/2;i>0;--i)maxHeapIfy(i);}/** *保持最大堆的性质,使根节点大于子节点 */void maxHeapIfy(int hole)    {        int child;        Comparable tmp = std::move(array[hole]);        for( ;hole*2<=currentSize;hole=child)        {            child=hole*2;             // if the right child exist,choose the max child            if( child != currentSize && array[ child + 1 ] > array[ child ])                ++child;            // if the max child greater than the father,exchange            if( array[child]>tmp)                array[hole]=std::move(array[child]);            else                break;        }        array[hole]=std::move(tmp);    }};int main(){vector<int> vec{4,1,3,2,16,9,10,14,8,7};BinaryHeap<int> heap{vec};heap.print();heap.increaseKey(9,15);heap.print();heap.insert(10);heap.print();vector<int> vecsort;heap.heapSort(vecsort);for(auto v:vecsort)cout<<v<<" ";cout<<endl;}


                                             
0 0
原创粉丝点击