【代码】c++堆的简单实现
来源:互联网 发布:2345好压mac版 编辑:程序博客网 时间:2024/06/06 01:46
堆对象的创建与实现的核心思想就是上调(adjustup)与下调(adjustdown)的算法思想,上调用于创建堆时,从第一个非叶子节点开始向根节点根据需求调整为大堆或者小堆
下调如图示:
当我们进行插入时,会影响堆的结构,这时我们用尾插,然后上调如图示:
接下来就可以创建堆类,代码如下仅供参考:
#include<iostream>#include<vector>template <class T>struct CompMax{bool operator()(const T& a, const T& b){return a > b;}};template <class T>struct CompMin{bool operator()(const T& a,const T& b){return a < b;}};template <class T,class Com=CompMax<T> >//仿函数做模板参数,可根据需求修改比较方法class Heap{public:Heap(const T* arr, size_t size, Com _comp):comp(_comp){_List.resize(size);int index = 0;for (index = 0; index < size; ++index){_List[index] = arr[index];}index = (_List.size()- 2) / 2;while (index>=0)_adjustdown(index--);}void Push(const T &x){_List.push_back(x);size_t index = _List.size() - 1;_adjustup(index);}void Pop(){_List.pop_back();}T& Top(){return _List[0];}protected:void _adjustup(size_t index){size_t child = index;size_t parent = (child - 1) / 2;while (child){if (child % 2){if (child + 1<_List.size())child =comp(_List[child],_List[child+1]) ? child : child + 1;}else{child = comp(_List[child] ,_List[child - 1]) ? child : child - 1;}if (!comp(_List[child],_List[parent])){std::swap(_List[parent], _List[child]);}child = parent;parent = (parent - 1) / 2;}}void _adjustdown(size_t index){size_t parent = index;size_t child = parent * 2 + 1;while (child < _List.size()){if (child + 1 < _List.size())child = comp(_List[child] , _List[child + 1]) ? child : child + 1;if (!comp(_List[parent], _List[child])){std::swap(_List[child], _List[parent]);parent = child;child = (parent + 1) * 2;}elsebreak;}}protected:vector<T> _List;Com comp;};
如有不足希望指正,如有问题也希望提出,谢谢-3-。
本文出自 “pawnsir的IT之路” 博客,请务必保留此出处http://10743407.blog.51cto.com/10733407/1771228
0 0
- 【代码】c++堆的简单实现
- 堆的简单实现
- 堆的简单实现
- 堆的简单实现
- [数据结构]堆排序的C语言简单实现
- 简单的C语言赫夫曼树实现代码
- 最小堆&&最大堆的实现(c++)
- 最小堆&&最大堆的实现(c++)
- 最小堆&&最大堆的实现(c++)
- 堆排序的C实现
- 堆排序的实现(c++)
- 简单的C语言栈的实现代码
- 简单的C语言二叉树的实现代码
- Windows下一个简单的日志系统的C代码实现
- 算法代码实现之堆排序,C/C++实现
- 用C语言实现一个简单的计算器代码
- 简单的C语言快速排序实现代码
- 简单的C语言归并排序实现代码
- 【智能指针的延伸】两种定制删除器的实现方法
- 【干货】容器适配器实现两个栈模拟队列
- 【代码】C++实现广义表及其测试用例
- 【代码】C++实现二叉树基本操作及测试用例
- 二叉树的线索化算法思想详解
- 【代码】c++堆的简单实现
- 堆排序算法思路详解
- 【代码】key-value模式下的哈希二次探测与简单的哈希类的实现
- 【代码】稀疏矩阵的压缩存储与转置算法
- LINUX下的几个常见的环境变量
- 【干货】C++哈希桶(开链法解决哈希冲突)类的实现
- 【干货】位图的实现与布隆过滤器
- Linux下find函数用法汇总
- 【随笔】Linux文件的三个时间属性