heap
2015-11-23 15:33
106 查看
//最大堆 #ifndef HEAP_H_ #define HEAP_H_ #include <vector> using namespace std; class Heap { private: vector<int> heapData; int heapSize; //堆中元素的个数 public: Heap(int *arr,int n); //构造函数,n为数组元素个数 void percolateUp(int index, int value); //从index(下标)上溯 void adjustHeap(int holeIndex, int value); //调整以holeIndex为根的子树为堆 void pushHeap(int addValue); void popHeap(int choose=0); //默认不删除,choose=1时,表示删除该元素,释放内存 void makeHeap(); void display(); void sort(); //排序 }; //构造函数 Heap::Heap(int *arr,int n) { heapSize = n; for (int i = 0; i < n; i++) heapData.push_back(arr[i]); makeHeap(); } //上溯 void Heap::percolateUp(int index, int value) { int holeIndex = index; int parent = (holeIndex - 1) / 2; while (holeIndex >0 && heapData[parent]<value) //**错过 { heapData[holeIndex] = heapData[parent]; holeIndex = parent; parent = (holeIndex - 1) / 2; } heapData[holeIndex] = value; } //调整以holeIndex为根的子树为堆,对应值为value,从上往下 void Heap::adjustHeap(int holeIndex, int value) { int topIndex = holeIndex; int rightChild = topIndex * 2 + 2; while (rightChild < heapSize) { if (heapData[rightChild - 1] > heapData[rightChild]) rightChild--; heapData[holeIndex]=heapData[rightChild]; holeIndex = rightChild; rightChild = 2 * rightChild + 2; //找到新的洞节点的右孩子 } if (rightChild == heapSize) { heapData[holeIndex] = heapData[rightChild - 1]; holeIndex = rightChild - 1; } heapData[holeIndex] = value; //**错过,STL源码剖析里面没有这个 percolateUp(holeIndex,value); //上溯调节 } //往堆中加入一个元素 void Heap::pushHeap(int addValue) { heapData.push_back(addValue); ++heapSize; adjustHeap(heapSize - 1, heapData[heapSize - 1]); } //往堆中取出一个元素 void Heap::popHeap(int choose) { int adjustValue = heapData[heapSize-1]; heapData[heapSize - 1] = heapData[0]; //将第一个放到堆尾; --heapSize; if (choose==1) heapData.pop_back(); adjustHeap(0, adjustValue); //**错过,是从上往下 } //生成堆 void Heap::makeHeap() { if (heapSize < 2) return; int holeIndex = (heapSize - 2) / 2; //最后一个节点的parent while (1) { adjustHeap(holeIndex, heapData[holeIndex]); if (holeIndex == 0) return; --holeIndex; } } //显示堆 void Heap::display() { for (int i = 0; i < heapSize; i++) cout << heapData[i] << " "; cout << endl; } //排序 void Heap::sort() { int temp = heapSize; while (heapSize > 0) popHeap(); heapSize = temp; } #endif
#include <iostream> #include "Heap.h" using namespace std; int main() { int a[9] = {0,1,2,3,4,8,9,3,5}; Heap heap1(a, 9); //heap1.pushHeap(7); //heap1.display(); //heap1.popHeap(); heap1.sort(); heap1.display(); return 0; }
相关文章推荐
- vim 自动补全插件 for nodejs
- java 拦截器、过滤器、监听器
- net中日期格式转换大全
- ROWNUMBER() OVER( PARTITION BY COL1 ORDER BY COL2)用法
- iOS-PCH File的快速导入方法和使用
- 【百度地图事件监听】
- Volley_ImageLoader
- 技术接受模型(TAM,Technology Acceptance Model)
- 转轮检测机电机控制
- BAT脚本开启、关闭IE代理服务器
- MYSQL 配置优化
- 问题事件名称: APPCRASH(解决方法)
- GeoPandas官方中文文档--译著
- 1050. String Subtraction
- resin 4.x 在MyEclipse配置
- 子窗口 向父窗口传值
- 优化方法-模拟退火法
- Js 正则表达式特殊字符含义
- GeoPandas官方中文文档--译著
- Jsp+Servlet+JavaBean经典MVC模式理解