I always agree with the idea that simple logic in code does not need to be commented, so I do not write comments, directly on the code:
#include <iostream>#include<deque>#include<limits>inlineintParent (Const inti) { returnStd::move (i%2? I1) /2: (I-2) /2);} InlineintLeft (Const inti) { returnStd::move (2* i +1);} InlineintRight (Const inti) { returnStd::move (2* i +2);}voidMaxheapify (std::d eque<int> &ideq,intnode) { intlargest =node; intLimit =ideq.size (); Auto Smallerthan= [&] (intChild) {return(Child < limit) && (Ideq[largest] <Ideq[child]); }; intLeftnode =Left (node); if(Smallerthan (Leftnode)) {Largest=Leftnode; } intRightnode =Right (node); if(Smallerthan (Rightnode)) {Largest=Rightnode; } if(Largest! =node) {Std::swap (ideq[largest], Ideq[node]); Maxheapify (Ideq, largest); }}STD::d eque<int> Buildmaxheap (std::d eque<int> &Ideq) {std::d eque<int>Heap (IDEQ); for(inti = ideq.size ()/2-1; I >-1; --i) {maxheapify (heap, i); } returnstd::move (heap);}voidHeapsort (std::d eque<int> &Ideq) {Auto Heap=buildmaxheap (Std::move (IDEQ)); for(inti = ideq.size ()-1; I >-1; --i) {Ideq[i]= Std::move (heap[0]); Heap.pop_front (); Maxheapify (Heap,0); }}intHeapmaximum (std::d eque<int> &heap) { Const intTopvalue = heap[0]; returnStd::move (Topvalue);}intHeapextractmax (std::d eque<int> &heap) { if(Heap.empty ()) {Std::cerr<<"Heap overfow!\n"; } intmax = Std::move (heap[0]); Heap.pop_front (); Maxheapify (Heap,0); returnStd::move (max);}voidHeapincreasekey (std::d eque<int> &heap,int&&node,int&&key) { if(Key <Heap[node]) {Std::cerr<<"This key was smaller than current key!\n"; } Heap[node]=key; intParentNode =0; while(Node >0) && (parentnode = Parent (node), Heap[parentnode] <key)) {Std::swap (Heap[parentnode], Heap[node]); Node=parentnode; }}voidMaxheapinsert (std::d eque<int> &heap,intkey) {Heap.push_back (Std::move (std::numeric_limits<int>:: Min ())); Heapincreasekey (Heap, heap.size ()-1, Std::move (key));}voidPrint (Conststd::d eque<int> &Ideq) { for(ConstAuto &Elem:ideq) {Std::cout<< Elem <<" "; }}intMain () {Std::ios::sync_with_stdio (false); std::d eque<int> ideq{5, -,2, -,7, -, -,9,4}; Auto Maxheap=buildmaxheap (IDEQ); Heapincreasekey (Maxheap,0, -); Heapincreasekey (Maxheap, Maxheap.size ()-1, +); Maxheapinsert (Maxheap, *); Print (MAXHEAP); Std::cout<<Std::endl; return 0;}
Of course there are many areas that need improvement, but also hope that the crossing more comments ha ~
Generics also need to abstract less<_ty> (_ty LHS, _ty RHS), and even left<_ty> (_ty index), right<_ty> (_ty index) and parent< _ty> (_ty) should also be abstracted. Just the purpose of this blog is to review the algorithm, so do not make too much discussion.
Of course it's just a purely practice algorithm, or python is better ...
And I'm not going to say that STL has a priority_queue<type> ...
C + + implements maximum heap ordering and maximum priority queue