heap

来源:互联网 发布:mac免费翻墙教程 编辑:程序博客网 时间:2024/05/22 00:08


//最大堆#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;  //最后一个节点的parentwhile (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;}


0 0