Self-feeling code to write a messy, this aspect to pay attention to.
Summarize:
1. In the use of similar types of vector<int>::size_type, it is important to pay attention to the conditions of the cycle of judgment, prone to overflow danger! So I finally lazy choice to use INT--.
2. The subscript represents the subtle difference between the number of elements represented. The transformation relationship between subscripts:
Parent node (i) = (i-1)/2; Left (i) =2*i+1 child Right (i) =2*i+2
classmax_heap{typedefintindex; Public: Max_heap (Constvector<int> &VEC): V (VEC) {build_heapify (v); } ~max_heap () {}; voidHeap_sort (); intHeap_max () {returnv[0]; } intHeap_extract_max (); voidInsert (intkey);Private: Vector<int>v; voidMax_heapify (vector<int> &vec, Index i,intHS); voidBuild_heapify (vector<int> &VEC);};voidmax_heap::max_heapify (Vector<int> &vec, Index i,intHS) { intL =2* i +1, r =2* i +2; intlargest =i; if(L < hs&&vec[l] >Vec[i]) largest=l; if(R < Hs&&vec[r] >Vec[largest]) largest=R; if(Largest! =i) {Swap (Vec[i], vec[largest]); Max_heapify (VEC, largest, HS); }}voidmax_heap::build_heapify (Vector<int> &VEC) { intHS =vec.size (); for(inti = (HS/2) -1; I >=0; --i) max_heapify (VEC, I, HS);}voidMax_heap::heap_sort () {intHS =v.size (); Build_heapify (v); for(inti = HS-1; I >=0; --i) {Swap (v[0], v[i]); Max_heapify (V,0, i); }}intMax_heap::heap_extract_max () {if(v.size () = =0) {Std::cout<<"Over flow"; return 0; } Else { inttemp = v[0]; Swap (v[0], v[v.size ()-1]); V.pop_back (); Max_heapify (V,0, V.size ()); returntemp; }}voidMax_heap::insert (intkey) {V.push_back (key); intSZ =v.size (); while(sz>=2&&key > V[sz/2-1]) {Swap (V[sz-1], V[sz/2-1]); SZ= SZ/2; }}
Maximum heap/Minimum heap/Priority queue Implementation Code (c + +)