The core idea of the creation and implementation of heap objects is to raise (Adjustup) and downgrade (Adjustdown) algorithm ideas, to increase the use of the heap, from the first non-leaf node to the root node according to demand to adjust to a large heap or small heap
Downward indication:
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7F/D5/wKiom1cvCpfjuPkkAAAkCLyIQjQ600.png "title=" Qq20160505224705.png "alt=" Wkiom1cvcpfjupkkaaakclyiqjq600.png "/>
When we insert, we affect the structure of the heap, and then we use the tail plug, and then we raise the following:
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/D5/wKiom1cvDRehwFD4AAAlAV7a9cM800.png "title=" 1.png " alt= "Wkiom1cvdrehwfd4aaalav7a9cm800.png"/>
Next you can create a heap class with the following code for reference only:
#include <iostream> #include <vector>template <class T>struct CompMax{bool Operator () (const t& a, const t& b) {return a > b;}}; Template <class t>struct compmin{bool operator () (Const t& a,const &NBSP;T&&NBSP;B) {return a < b;}}; template <class t,class com=compmax<t> >//copy function template parameters can be modified according to the requirements of the comparison method class heap{ Public:heap (Const t* arr, size_t size, com _comp): Comp (_comp) {_List.resize (size) ;int index = 0;for (Index = 0; index < size; ++index) {_ List[index] = arr[index];} index = (_list.size ()- 2) / 2;while (index>=0) _adjustdown (index--);} Void push (const t &x) {_list.push_back (x); Size_t index = _list.size () - 1;_adjustup (index);} Void pop () {_list.pop_baCK ();} T& top () {return _list[0];} Protected:void _adjustup (size_t index) {size_t child = index;size_t parent = (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_t index) {size_t parent = index;size_t child = parent * 2 + 1;while (Child < _list.size ()) {if (child + 1 < _list.size ()) Child = comp (_list[child] , _list[child +&NBSP;1]) ? child : child + 1;if (!comp (_list[parent], _list[child])) { Std::swap (_list[child], _list[parent]);p arent = child;child = (parent + 1) * 2;} Elsebreak;}} protected:vector<t> _list; com comp;};
If there is insufficient hope to correct, if there are problems also hope to put forward, thank you.
This article is from the "Pawnsir It Road" blog, so be sure to keep this source http://10743407.blog.51cto.com/10733407/1771228
Simple implementation of the "code" C + + heap