// ------------------- min heap -------------------------- #include<iostream> #include<vector> #include<queue> usingnamespacestd;
constint MAX_N = 100; int heap[MAX_N],sz=0; //sz is global variable, meaning the lengh of heap
voidheap_push(int x){ //own node's num. int node_index = sz++; while (node_index > 0) { int p = (node_index-1)/2; //i's parent if (heap[p] <= x) { break; // sequence is ok } // parent's value put down, node value go up heap[node_index] = heap[p]; node_index = p; } heap[node_index] = x; }
intheap_pop(){ // min (root) int rec = heap[0]; // the new temp root value, get it for compare and move it int x = heap[--sz]; //replace from the root int i = 0; while (i*2+1 < sz) { //compare the children value int a = i*2+1; int b = i*2+2; if (b < sz && heap[b] < heap[a]) { a = b; } // sequence is right if (heap[a] >= x) { break; } // child's value go up heap[i] = heap[a]; i=a; } heap[i] = x; return rec; }
intmain(){ //push(3); heap_push(9); heap_push(2); heap_push(6); for (int i=0; i<sz; i++) { cout<<heap[i]<<endl; } cout<<"pop:"<<heap_pop()<<endl; cout<<"pop:"<<heap_pop()<<endl; // ------ standard package is the max queue ------ priority_queue<int> qqueue; qqueue.push(-9); qqueue.push(-2); qqueue.push(-6); //loop until it is empty while (!qqueue.empty()) { cout<<-1 * qqueue.top()<<endl; qqueue.pop(); } return0; }