A few days ago to deal with the work of things, indeed delayed a few days, resulting in a blog stop more, this morning to see the algorithm introduction of the heap sequencing, want to use C + + implementation, when practicing practiced hand.
The introduction of the algorithm is used in the beginning of the container of number 1, then the implementation of the method is either to the STL container packaging, build a container with a starting number of 1, or according to the starting number of 0. Think of a moment always feel that the first kind of fits egg pain, is written to only show my understanding of the STL container rather than the understanding of the algorithm, so if you really understand the idea of heap sequencing, then regardless of the value of the starting number is the same. So I chose the second scenario with the following code:
#include <iostream>#include<deque>inlineintLeft (inti) { return 2* i +1;} InlineintRight (inti) { return 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); }}voidPrint (Conststd::d eque<int> &Ideq) { for(ConstAuto &Elem:ideq) {Std::cout<< Elem <<"\ t"; }}intMain () {Std::ios::sync_with_stdio (false); std::d eque<int> ideq{5, -,2, -,7, -, -,8,4}; Print (IDEQ); Heapsort (IDEQ); Std::cout<<"\ n"; Print (IDEQ); Std::cout<<Std::endl; return 0;}
In fact, I think the use of forward_list seems more appropriate, but the use of no deque convenient, so ...
In the meantime because of some careless, led to some small problems, so have to say VS debugging ability is strong AH ...
C + + heap sequencing