一个简单的Heap实现
来源:互联网 发布:windows下测试udp端口 编辑:程序博客网 时间:2024/05/12 05:57
以下代码实现了一个堆,可以传入仿函数来决定生成最大堆或最小堆。
#ifndef _HEAP_#define _HEAP_#include"../Vector/Vector.h"#include<string>using namespace std;template<typename T>class Less{public: bool operator()(const T& t1,const T& t2) { return t1<t2; }};template<typename T>class Greater{public: bool operator()(const T& t1,const T& t2) { return t1>t2; }};template<typename T,typename Compair=Less<T>>class heap{public: heap():_vector() {} heap(const MyVector<T>& v):_vector(v) { make_heap(); } ~heap() {} heap(const heap& h) { _vector=h._vector; } heap& operator=(const heap& h) { _vector=h._vector; } const T& top() { if(empty()) throw new string("heap is null!"); return _vector[0]; } void make_heap() { int i; int n=_vector.size(); for(i=n/2;i>=0;--i) { _JustDown(i,n); } } void push_heap(const T& t) { Compair cp; _vector.push_back(t); int i=_vector.size()-1; for(;i>=0;) { if(cp(_vector[i],_vector[i/2])) { swap(_vector[i],_vector[i/2]); i=i/2; } else { break; } } } bool empty() { return _vector.empty(); } size_t size() { return _vector.size(); } T pop_heap() { if(empty()) throw new string("heap is null!"); swap(_vector[0],_vector[_vector.size()-1]); T tmp=_vector[_vector.size()-1]; _vector.pop_back(); _JustDown(0,_vector.size()); return tmp; } void sort_heap() { if(empty()) throw new string("heap is null!"); int i=_vector.size()-1; for(;i>0;) { swap(_vector[0],_vector[i]); _JustDown(0,i); i--; } } void Print() { int i; for(i=0;i<_vector.size();++i) { cout<<_vector[i]<<" "; } cout<<endl; }private: void _JustDown(int s,int n) { Compair cp; if(n<=1) return; if(s>=n) return; int i; for(i=s;i<n;) { if(i*2+2<n) { int select=cp(_vector[i*2+1],_vector[i*2+2])?i*2+1:i*2+2; select=cp(_vector[select],_vector[i])?select:i; if(i!=select) { swap(_vector[i],_vector[select]); i=select; } else { break; } } else if(i*2+1<n) { if(cp(_vector[i*2+1],_vector[i])) swap(_vector[i],_vector[i*2+1]); i=i*2+1; } else { break; } } }private: MyVector<T> _vector;};#endif
以上
如果你有任何想法或是可以改进的地方,欢迎和我交流!
完整代码及测试用例在github上:点我前往
本文首发于www.sbrave.cn
【完】
0 0
- 一个简单的Heap实现
- 理解 heap --- 实现一个简单的 malloc
- STL 简单 binary heap 的实现
- 用数组实现一个简单的heap(最大堆)结构
- 一个不错的模板Heap实现及Heap排序的实现
- 自己实现的简单heap max_heap和min_heap 还有sort
- 堆的实现 Heap
- 堆(heap)的实现
- Heap的java实现
- 一个简单singleton的实现
- 一个简单的SOA实现
- 一个HUD的简单实现
- 哈希表一个简单的实现
- 一个简单的Matrix实现
- 一个四叉树的简单实现
- 一个简单文件系统的实现
- 一个简单的信号量实现
- 一个简单的RTTI实现
- jquery: prop 与 attr
- .htaccess file not work
- android文件上传的一些问题
- java IO流之四 使用转换流InputStreamReader和OutputStreamWriter
- 浅谈Android Studio单元测试步骤
- 一个简单的Heap实现
- ionic 进入二级目录以后隐藏底部导航栏(tabs)
- BenchmarkSQL简介+简用
- Android开发之二维码ZXing vs ZBar
- iOS开发如何判断一个字符串里只有纯数字
- nosql和关系型数据库的比较
- getCurrentSession 与 openSession() 的区别
- how to solve git detached HEAD
- java中的字符串的截取