Reference: seven-heap and heap sequencing of vernacular classical algorithm series
1#include <iostream>2#include <climits>3#include <vector>4 using namespacestd;5 6 namespaceHeap {7 8 //Insert an element to a heap9 voidInserttoheap (vector<int>& H,intx) {Ten h.push_back (x); One intn =h.size (); A - inti = n-1; - intp = (I-1) /2;//Parent the inttemp =x; - while(P >=0&& I! =0) { - if(H[p] <=temp) { - Break; + } -H[i] =H[p]; +i =p; Ap = (I-1) /2; at } -H[i] =temp; - } - - voidMinheapfixdown (vector<int>& H,intIintN) { - intTMP =H[i]; in intj =2* i +1; - while(J <N) { to if(j +1< n && h[j +1] <H[j]) { +J + +; - } the if(H[j] >=tmp) { * Break; $ }Panax NotoginsengH[i] =H[j]; -i =J; thej =2* i +1; + } AH[i] =tmp; the } + - //Delete an element from a heap $ voidDeletefromheap (vector<int>&h) { $ if(H.empty ()) - return; - if(h.size () = =1) { the h.clear (); - return;Wuyi } the intn =h.size (); -h[0] = H[n-1]; WuH.erase (H.end ()-1); -Minheapfixdown (H,0, n); About } $ - //Make an array Minimum heap - voidHeaparray (vector<int>&h) { - intn =h.size (); A for(inti = n/2-1; I >=0; i--) { + Minheapfixdown (h, I, n); the } - } $ the voidHeapsort (vector<int>&h) { the intn =h.size (); thevector<int> tmp =h; the for(inti =0; I < n; i++) { -H[i] = tmp[0]; in deletefromheap (TMP); the } the } About the voidPrintheap (vector<int>&Testvec) { the for(size_t i =0; I < testvec.size (); i++) { theStd::cout << Testvec[i] <<","; + } -Std::cout <<Std::endl; the }Bayi } the ; the - intMain () { -vector<int> Testvec = {0,3,9,1,3,5 }; the Heap::heaparray (Testvec); the Heap::p rintheap (Testvec); the the Heap::d eletefromheap (Testvec); - Heap::p rintheap (Testvec); the theHeap::inserttoheap (Testvec,4); the Heap::p rintheap (Testvec);94 the Heap::heapsort (Testvec); the Heap::p rintheap (Testvec); the 98 return 0; About}
Interview 9: Array heap, heap insert, heap delete, heap sort