Maximum heap/Minimum heap/Priority queue Implementation Code (c + +)

Source: Internet
Author: User

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 + +)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.