【代码】c++堆的简单实现
堆对象的创建与实现的核心思想就是上调(adjustup)与下调(adjustdown)的算法思想,上调用于创建堆时,从第一个非叶子节点开始向根节点根据需求调整为大堆或者小堆
下调如图示:
当我们进行插入时,会影响堆的结构,这时我们用尾插,然后上调如图示:
接下来就可以创建堆类,代码如下仅供参考:
#include<iostream>#include<vector>template<classT>structCompMax{booloperator()(constT&a,constT&b){returna>b;}};template<classT>structCompMin{booloperator()(constT&a,constT&b){returna<b;}};template<classT,classCom=CompMax<T>>//仿函数做模板参数,可根据需求修改比较方法classHeap{public:Heap(constT*arr,size_tsize,Com_comp):comp(_comp){_List.resize(size);intindex=0;for(index=0;index<size;++index){_List[index]=arr[index];}index=(_List.size()-2)/2;while(index>=0)_adjustdown(index--);}voidPush(constT&x){_List.push_back(x);size_tindex=_List.size()-1;_adjustup(index);}voidPop(){_List.pop_back();}T&Top(){return_List[0];}protected:void_adjustup(size_tindex){size_tchild=index;size_tparent=(child-1)/2;while(child){if(child%2){if(child+1<_List.size())child=comp(_List[child],_List[child+1])?child:child+1;}else{child=comp(_List[child],_List[child-1])?child:child-1;}if(!comp(_List[child],_List[parent])){std::swap(_List[parent],_List[child]);}child=parent;parent=(parent-1)/2;}}void_adjustdown(size_tindex){size_tparent=index;size_tchild=parent*2+1;while(child<_List.size()){if(child+1<_List.size())child=comp(_List[child],_List[child+1])?child:child+1;if(!comp(_List[parent],_List[child])){std::swap(_List[child],_List[parent]);parent=child;child=(parent+1)*2;}elsebreak;}}protected:vector<T>_List;Comcomp;};
如有不足希望指正,如有问题也希望提出,谢谢-3-。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。