关于堆的操作
来源:互联网 发布:恐怖整蛊软件 编辑:程序博客网 时间:2024/03/29 23:19
/*堆操作来源:Data Structures with C++ Using STL*/#include <iostream>#include <vector>#include <stdlib.h>#include <functional>using namespace std;//调整堆的顺序template <typename T, typename Compare>void adjustHeap(vector<T>& v, int first, int last, Compare comp){int currentPos, childPos;T target;currentPos = first;target = v[first];childPos = 2 * currentPos + 1;while (childPos <= last - 1){//判断左右子节点的大小if ((childPos + 1 <= last - 1) && comp(v[childPos + 1], v[childPos]))childPos = childPos + 1;if (comp(v[childPos], target)){v[currentPos] = v[childPos];currentPos = childPos;childPos = 2 * currentPos + 1;}elsebreak;}v[currentPos] = target;}//堆的插入操作template <typename T, typename Compare>void pushHeap(vector<T> &v, int last, Compare comp){int currentPos, parentPos;T target;currentPos = last - 1;parentPos = (currentPos - 1) / 2;target = v[last - 1];//遍历父结点的路径while (currentPos != 0){if (comp(target, v[parentPos])){v[currentPos] = v[parentPos];currentPos = parentPos;parentPos = (currentPos - 1) / 2;}elsebreak;}v[currentPos] = target;}//从堆中删除数据template <typename T, typename Compare>void popHeap(vector<T>& v, int last, Compare comp){T temp;temp = v[0];//交换堆顶元素和最后一个元素v[0] = v[last - 1];v[last - 1] = temp;adjustHeap(v, 0, last - 1, comp);//调整0-(last-1)之间的次序}//向量堆化template <typename T, typename Compare>void makeHeap(vector<T>& v, Compare comp){int heapPos, lastPos;lastPos = v.size();heapPos = (lastPos - 2) / 2;while (heapPos >= 0){adjustHeap(v, heapPos, lastPos, comp);heapPos--;}}//堆排序template <typename T, typename Compare>void heapSort(vector<T>& v, Compare comp){makeHeap(v, comp);int i, n = v.size();for (i = n; i > 1; i--){popHeap(v, i, comp);}}void main(){int arr[] = { 5, 9, 2, 7, 1, 3, 8 };int i, arrSize = sizeof(arr) / sizeof(int);vector<int> vA, vB;for (i = 0; i < arrSize; i++){vA.push_back(arr[i]);pushHeap(vA, vA.size(), greater<int>());vB.push_back(arr[i]);pushHeap(vB, vB.size(), less<int>());}cout << "Maximum heap:";while (!vA.empty()){popHeap(vA, vA.size(), greater<int>());cout << vA.back() << " ";vA.pop_back();}cout << endl;cout << "Minimum heap:";while (!vB.empty()){popHeap(vB, vB.size(), less<int>());cout << vB.back() << " ";vB.pop_back();}cout << endl;//堆排序vector<int> v = { 5, 9, 2, 7, 1, 3, 8 };heapSort(v, greater<int>());for (i = 0; i < v.size(); i++)cout << v[i] << " ";cout << endl;heapSort(v, less<int>());for (i = 0; i < v.size(); i++)cout << v[i] << " ";cout << endl;}
阅读全文
0 0
- 关于堆的操作
- 关于堆操作的进一步研究
- L2-012. 关于堆的判断 (堆操作)
- 关于堆得相关操作
- 堆的综合操作
- 堆的操作
- STL的堆操作
- 堆的各种操作
- 堆的操作
- 堆的基本操作
- 堆的基本操作
- 堆的基本操作
- 堆的操作
- STL的堆操作
- 堆的各种操作
- python 堆的操作
- 堆的相关操作
- 堆的操作
- JAVA虚拟机初步学习之类的加载
- Mybatis动态数据源实现
- Python--正则匹配
- 关闭WIN10系统更新
- 目标检测之一(传统算法和深度学习的源码学习)
- 关于堆的操作
- 更新boot后,WLAN无法使用
- DAY4-2017-11-20
- Gradle 与 Android的三生三世:是我构建了你,你必将依赖于我
- 算法题目:A为矩阵,求S(n)=A^1+A^2+...+A^n 小技巧
- 区分string中的字母和汉字
- CocosCreator的ToggleGroup组件使用
- 买一台 iPhone X,还是创建一家未来的独角兽?
- Otter单向同步配置