堆与优先级队列实现
2017-05-10 21:50
176 查看
#include<iostream> 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 Compare=Less<T>> class Heap { public: // 创建一个空堆 Heap() {} Heap(const T array[], size_t size) { _heap.resize(size); for(size_t idx=0;idx<size;idx++) { _heap[idx]=array[idx]; } int root=(_heap.size()-2)>>1; for(;root>=0;root--) { _AdjustDown(root); } } size_t Size()const { return _heap.size(); } const T& Top()const { assert(!_heap.empty()); return _heap[0]; } bool Empty()const { return _heap.empty(); } void Insert(const T& data) { _heap.push_back(data); if(_heap.size()>1) { _AdjustUp(); } } void Remove() { assert(!_heap.empty()); if(_heap.size()>1) { std::swap(_heap[0],_heap[_heap.size()-1]); _heap.pop_back(); _AdjustDown(0); } } protected: void _AdjustDown(size_t parent) { size_t child=parent*2+1; while(child<_heap.size()) { Compare com; if(child+1<_heap.size()&&com(_heap[child+1],_heap[child])) child+=1; if(com(_heap[child],_heap[parent])) { std::swap(_heap[parent],_heap[child]); 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(Compare()(_heap[child],_heap[parent])) { std::swap(_heap[child],_heap[parent]); child=parent; parent=(child-1)>>1; } else return; } } protected: std::vector<T> _heap; }; /////优先级队列 template<class T, class Compare = Less<T>> class PriorityQueue { public: PriorityQueue() {} void Push(const T& data) { _hp.Insert(data); } void Pop() { _hp.Remove(); } const T& Top()const { return _hp.Top(); } size_t Size()const { return _hp.Size(); } bool Empty()const { return _hp.Empty(); } protected: Heap<T, Compare> _hp; }; int main() { int arr[]={53,17,78,9,45,65,87,23}; Heap<int,Greater<int>> s(arr,8); return 0; }
相关文章推荐
- 基于最小二叉堆的优先级队列-C#实现,以此为基础的K路合并排序算法
- 关于优先级队列的实现
- 优先级队列实现哈夫曼树的编码和译码
- 优先级队列实现哈夫曼树的编码和译码
- 堆和堆排序(堆实现优先级队列)
- 用链表实现优先级队列
- 用优先级队列实现先进先出队列;
- 第六章堆排序之“优先级队列实现先进先出队列和栈”(练习6.5-6)
- 算法导论Java实现-优先级队列(6.5章节)
- 读《算法导论》我来C语言实现(3)——堆排序和优先级队列
- 顺序表实现优先级队列
- 优先级队列——用C++模板实现
- C语言实现的优先级队列
- 基于大顶堆实现的最大优先级队列
- 泛型优先级队列的实现
- 算法-----堆结构实现优先级队列
- W. :利用最小优先级队列实现对k个已序队列的合并排序。习题6.5-8
- 优先级队列的Java ,C++ STL,堆实现
- 优先级队列(可用堆实现)
- 循环队列与优先级队列的Java实现