算法导论—堆
来源:互联网 发布:日语培训 知乎 编辑:程序博客网 时间:2024/04/28 04:43
<pre name="code" class="cpp">#include <vector>#include <iostream>using namespace std;class UnderflowException { };template<typename Comparable>class BinaryHeap{public:explicit BinaryHeap(int capacity=100):array(capacity+1),currentSize(0){ }explicit BinaryHeap(const vector<Comparable> &items):array(items.size()+10),currentSize(items.size()){for(int i=0;i<items.size();++i)array[i+1]=items[i];buildMaxHeap();}bool isEmpty() const{return currentSize==0;}int currSize() const{return currentSize;}void print(){for(int i=1;i<=currentSize;++i)cout<<array[i]<<" ";cout<<endl;}const Comparable& findMax() const{if (isEmpty())throw UnderflowException{ };return array[1];}//Increase the value in position i to keyint increaseKey(int i,const Comparable &key){if (key<array[i]){cout<<"new key is smaller than current key,can not change"<<endl;return -1;}array[i]=key;while(i>1&&array[i/2]<array[i]){std::swap(array[i/2],array[i]);i=i/2;}return 0;}//Insert the x into the heapvoid insert(const Comparable &x){if (currentSize==array.size()-1)array.resize(array.size()*2);int hole=++currentSize;array[hole]=INT_MIN;increaseKey(hole,x);}/* *Remove the maximum item and return it *Throws Underflow if empty */ int deleteMax() { if(isEmpty()) throw UnderflowException{ }; int tmp=array[1]; std::swap(array[1],array[currentSize--]); maxHeapIfy(1); return tmp; } /** *heapSort */ void heapSort(vector<Comparable> &vec) { while(currentSize) { int tmp=deleteMax(); vec.push_back(tmp); } }private:int currentSize; //number of elements in heapvector<Comparable> array;/** *Establish heap order property from an arbitrary *arrangement of items.Runs in nlgn time. */void buildMaxHeap(){for(int i=currentSize/2;i>0;--i)maxHeapIfy(i);}/** *保持最大堆的性质,使根节点大于子节点 */void maxHeapIfy(int hole) { int child; Comparable tmp = std::move(array[hole]); for( ;hole*2<=currentSize;hole=child) { child=hole*2; // if the right child exist,choose the max child if( child != currentSize && array[ child + 1 ] > array[ child ]) ++child; // if the max child greater than the father,exchange if( array[child]>tmp) array[hole]=std::move(array[child]); else break; } array[hole]=std::move(tmp); }};int main(){vector<int> vec{4,1,3,2,16,9,10,14,8,7};BinaryHeap<int> heap{vec};heap.print();heap.increaseKey(9,15);heap.print();heap.insert(10);heap.print();vector<int> vecsort;heap.heapSort(vecsort);for(auto v:vecsort)cout<<v<<" ";cout<<endl;}
0 0
- 算法导论—堆
- 算法导论—最小堆
- 学习算法导论——堆排序
- 算法导论笔记——堆排序
- 算法导论——最大堆
- 算法导论—堆排序C++实现
- 算法导论—堆排序(python)
- 《算法导论》— Chapter 6 堆排序
- 算法导论 堆排序
- 算法导论--堆排序
- 【算法导论】 堆排序
- 算法导论-----堆排序
- 【算法导论】堆排序
- 算法导论-堆排序
- 堆排序--算法导论
- 算法导论:堆排序
- [算法导论]最大堆
- 算法导论:堆排序
- 快速排序问题
- ios 搭建phonegap-2.9.1环境 ,打包流程
- uva 1471 Defense Lines (降低复杂度)
- 《数据结构编程实验》 4.2.2VERY EASY !!!
- DSP软件开发中常用的滤波算法
- 算法导论—堆
- Java笔记(一)【Java从入门到精通—韩顺平】
- 数组Array及其工具类的使用
- POJ1195(二维线段树)
- LEFT JOIN,INNER JOIN区别
- 测试博客
- Linux进程间通信
- 安卓中获取一些状态
- 黑马程序员——集合基础(一)