最小堆实现

来源:互联网 发布:农村人口老龄化数据 编辑:程序博客网 时间:2024/06/07 10:17
#include <iostream>#include <vector>#include <time.h>#include <stdlib.h>using namespace std;template <typename Comparable>class BinaryHeap{public:BinaryHeap (const vector<Comparable> &s):element(s) {MaxIndex=maxIndex();printCurrentState();buildHeap();}bool isEmpty(){return element.size()<=1;}void insert(Comparable value){element.push_back(value); //insert a value++MaxIndex;percolateUp();            //build the heap}void deleteMin(Comparable &s){if(isEmpty())return;s=element[1];element[1]=element[MaxIndex];element.pop_back();--MaxIndex;if(!isEmpty())percolateDown(1);}private:vector<Comparable> element;int MaxIndex;void buildHeap(){for(int i=MaxIndex/2;i>0;--i){percolateDown(i);}}int maxIndex(){return element.size()-1;}void percolateDown(int index){Comparable tmp=element[index];int childIndex;for(;index*2<=MaxIndex;index=childIndex){childIndex=2*index;if(childIndex<MaxIndex&& element[childIndex]>element[childIndex+1])++childIndex;if(element[childIndex]<tmp)element[index]=element[childIndex];elsebreak;}element[index]=tmp;//printCurrentState();}void printCurrentState(){for(int i=1;i<=MaxIndex;++i)cout<<element[i]<<" ";cout<<endl;for(int i=1;i<=MaxIndex;++i)cout<<i<<" ";cout<<endl;cout<<endl;cout<<endl;}void percolateUp(){int hole=MaxIndex;Comparable tmp=element[hole];int parent;for(;hole/2>0;hole=parent){parent=hole/2;if(element[parent]>tmp)element[hole]=element[parent];elsebreak;}element[hole]=tmp;}};int main(){srand((unsigned)time(0));vector<int> s;for (int i=0;i<10;++i){s.push_back(rand()%10);cout<<s[i]<<" ";}cout<<endl;BinaryHeap<int> heap(s);//heap.insert(5);while(!heap.isEmpty()){int s=-100;heap.deleteMin(s);cout<<s<<" ";}cout<<endl;system("pause");}


还没理解透彻就编了,最终花了很多时间找问题出在哪里

0 0