堆顶元素的获取与删除
2016-03-19 08:44
295 查看
#include<iostream> using namespace std; class Heap { private: int *data, size; public: Heap(int length_input) { data = new int[length_input]; size = 0; } ~Heap() { delete[] data; } void push(int value) { data[size] = value; int current = size; int father = (current - 1) / 2; while (data[current] > data[father]) { swap(data[current], data[father]); current = father; father = (current - 1) / 2; } size++; } void output() { for (int i = 0; i < size; i++) { cout << data[i] << " "; } cout << endl; } int top() { return data[0]; } void update(int pos,int n) { int lchild=2*pos+1,rchild=2*pos+2; int max_value=pos; if( lchild<n && data[lchild]>data[max_value] ) { max_value=lchild; } if(rchild<n&&data[rchild]>data[max_value]) { max_value=rchild; } if(max_value!=pos) { swap(data[pos],data[max_value]); update(max_value,n); } } void pop() { swap(data[0],data[size-1]); size--; update(0,size); } }; int main() { int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 }; Heap heap(100); for (int i = 0; i < 10; i++) { heap.push(arr[i]); } heap.output(); cout<<heap.top()<<endl; heap.pop(); heap.output(); return 0; }
相关文章推荐
- oracle和mysql和.net的关联
- jsp和application和ant的关联
- app上传
- struts2和nginx和c++的关联
- commonio和javascript和nginx的关联
- mySql 数据库存储位置的查找及更改
- tomcat和groovy和samba的关联
- lua和html和aspx的关联
- mangodb和nginx和jetty的关联
- javascript和commonio和application的关联
- ant和jsp和sqlplus的关联
- mysql和dos和javascript的关联
- emordnolaPtsetrohS.214
- html和javascript和windows的关联
- perl和tomcat和mangodb的关联
- html和plsql和jquery的关联
- wireshark排查打印机问题
- Android画图最基本的三个对象(Color,Paint,Canvas)
- plsql和jquery和apache的关联
- jquery和context和lua的关联