#include <iostream>using namespacestd;inta[]={0,4,1,3,2, -,9,Ten, -,8,7};intLeftinti) { return 2*i;}intRightinti) { return 2*i+1;}intParentinti) { returni/2;}voidHeapinti) { intL=Left (i); intR=Right (i); intLarget; if(l<=Ten&&A[l]>A[i]) {Larget=l; } ElseLarget=i; if(r<=Ten&& a[r]>A[larget]) {Larget=R; } if(larget!=i) { intt=A[larget]; A[larget]=A[i]; A[i]=T; Heap (Larget); }}intMain () {//Heap (2);//observing rules that do not conform to the maximum heap from the second position//Rebuild Heap: for(intI=Ten/2+1; i>=1; i--) {heap (i); } for(intI=1; i<=Ten; i++) {cout<<A[i]<<Endl; } System ("Pause"); return 0;} Rebuild the heap, starting from the nodes of non-leaf nodes and rebuilding the largest heap from bottom to top! is the call to maintain the maximum heap method. Heap sorting algorithm:} Heap and Priority queue operations: #include<iostream>using namespacestd;//int a[]={0,16,4,10,14,7,9,3,2,8,1};inta[]={0,4,1,3,2, -,9,Ten, -,8,7};intlen=0;intLeftinti) { return 2*i;}intRightinti) { return 2*i+1;}intPartent (inti) { returni/2;}intLength () { for(intI=1;; i++){ if(a[i]!=0) Len++; Else Break; } returnLen;}//maintain the nature of the heap, n is the position that does not meet the maximum heap, less than the situation of two child nodesintHeapintN) { intL,r,larget; L=Left (n); R=Right (n); if(a[n]<a[l]&&l<=Len) {Larget=l; }ElseLarget=N; if(a[r]>a[larget]&&r<=len) Larget=R; if(larget!=N) { intt=A[n]; A[n]=A[larget]; A[larget]=T; Heap (Larget); } return 0;}//Build a heapvoidbuildheap () {//start with the leaf knot. for(inti=len/2;i>0; i--) {heap (i); }}//Heap sorting algorithm: maximum element is a[1], take away the largest element, length minus onevoidHeapsort () {buildheap (); //to sort so that the largest element is in the first position intleng=Len; for(inti=leng;i>=2; i--){ intt=a[1]; a[1]=A[i]; A[i]=T; Len--; Heap (1); }}//The following method is the priority queue//get the largest element: for the largest heap, the largest element is the firstintMaximun () {returna[1];}//get the maximum element and remove it,intextact () {intmax=a[1]; a[1]=A[len]; Len--; Heap (1); returnMax;}//Insert (X,K) increases the data in the X position to K, which may cause the maximum heap to changevoidInsertintXintk) {A[x]=K; if(x!=1){ while((x>1) && (a[x]>a[partent (x)])) { //children larger than parents, this is a relatively simple situation, the replacement of parent nodes can be intt=A[x]; A[X]=a[partent (x)]; A[partent (x)]=T; X=partent (x); } }}//inserts a key into the collectionvoidInsertkey (intkey) {Len+=1; A[len]=- +; Insert (Len,key);}intMain () {length (); intL=Len; //Heap (2);buildheap (); //Insert (2,20); //Cout<<maximun () <<endl; //cout<<extact () << "= = =" <<endl; //heapsort ();Insertkey ( the); for(intI=1; i<=l+1; i++) {cout<<a[i]<<Endl; } System ("Pause"); return 0;}
Heap and Priority queue