Basic idea: Both operations are proportional to the depth of the tree, so the complexity O (log (n));
Push (): When a value is inserted into the heap, the value is first inserted at the end of the heap, and then continuously upward until no size is reversed.
Pop (): When a value is taken out of the heap, the value of the last node of the heap is first copied to the root node, and the last node is deleted, and then it is switched downward until there is no size upside down, and if there are two sons at the time of the downward exchange, select the smaller (if exchangeable) exchange.
Array implementations:
1#include <cstdio>2 Const intMAXN =10000;3 intHEAP[MAXN], sz=0;4 5 voidPushintx) {6 inti = sz++;7 while(I >0) {8 intp = (I-1) /2;//P is the number of the Father node9 if(Heap[p] <= x) Break;//exit if no size is reversedTenHeap[i] = heap[p];//Put your father's node down and put yourself up . Onei =p; A } -Heap[i] = x;//put x in the right place - } the - intpop () { - intRET = heap[0];//Minimum Value - intx = Heap[--sz];//to mention the value of the root + - inti =0;//swap down from the root + whileI2+1< SZ) {//maybe only one son . A intA = i *2+1, B = i *2+2;//number of two sons at if(b < sz && heap[b] < heap[a]) a=b;//if the right son exists and the value is smaller than the left son, swap - if(Heap[a] >= x) Break;//If you can't swap, quit . -Heap[i] = Heap[a];//bring up the values of your son. -I=A; - } -Heap[i] =x; in returnret; - } to + intMain () - { thePush1); *Push2); $PushTen);Panax NotoginsengPush7); -Push4); the + intX1 =pop (); A intx2 =pop (); the +printf"%d%d\n", x1,x2); - for(inti =0; i< sz; i++) $printf"%d", Heap[i]); $ return 0; -}
Stl:
Priority_queue is the maximum value that is removed by default.
Priority_queue<int, Vector<int>, greater<int> >que; From small to large
Priority_queue<int, Vector<int>, less<int> >que; From big to small
1#include <iostream>2#include <queue>3 using namespacestd;4 5 intMain () {6priority_queue<int>que;7 8Que.push (5);9Que.push (2);TenQue.push (1); One A while(Que.size ()) { -cout << que.top () <<Endl; - Que.pop (); the } - return 0; -}
Two implementations of the heap (arrays and STL)