最小堆实现
来源:互联网 发布:农村人口老龄化数据 编辑:程序博客网 时间: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
- 最小堆的实现
- 最小堆的实现
- 最小堆的实现
- Dijkstra+最小堆实现
- 数组实现最小堆
- Java最小堆实现
- 最小堆实现
- 1.最小堆实现
- 最小堆&&最大堆的实现(c++)
- 最小堆&&最大堆的实现(c++)
- 最小堆与最大堆的实现
- 数据结构二叉堆C++实现 最小堆
- 最小堆&&最大堆的实现(c++)
- 手工实现堆(最小堆)
- 最大堆与最小堆的实现
- 最大堆、最小堆C++实现
- 最小优先队列--堆实现
- 最小堆的C++实现
- noip 2011 选择客栈
- java垃圾回收算法
- 1.8 C语言的文件系统
- WINCE--流设备驱动简介及往BSP添加
- Microsoft Interview: In binary tree, find two nodes' nearest common father
- 最小堆实现
- 2.3-删除链表中间节点
- 山东省2013高职分数线
- 进程与线程的一个简单解释
- 用Java Serialization实现任意文件网络传输
- 判断对象在堆上的代码例子
- Java实现线性表
- UVA10650 - Determinate Prime - 数论
- 九:基于xmpp的聊天