The heap is like a two-prong tree.
The most important property of the heap is that the value of the son must not be less than the father's value. The nodes of the tree are arranged in a compact order from top to bottom, from left to right.
Insert Data push
First, insert the data at the end of the heap and raise it upward until no size is reversed
"Delete Data" pop
Remove the smallest data from the heap
The value of the last node in the heap is copied to the root node first, and the last node is deleted. Then continue to swap downward until no size is reversed;
In the process of downward switching, if there are two sons, then a smaller interchange with them (if the son is smaller than himself).
"Operational complexity of the heap"
Both operations are proportional to the depth of the tree. Therefore, if there are n elements, then the complexity of each operation is O (LOGN);
"Implementation of the heap"
Each element is numbered from left to right in order from top to bottom and stored in an array, at which point the son's number satisfies the following properties
1. The left son's number is its own number x 2 + 1;
2. The right son's number is its own number x 2 + 2;
#include <iostream>using namespace Std;const int Maxn=10000;class priority_q{ Public:priority_q () {sz = 0;//size initialized to 0;}void push (int x); int pop (); int size () {return this->sz;} Private:int Heap[maxn],sz; };void priority_q::p ush (int x) {int i = sz++;while (i > 0) {//Father node number int p = (i-1)/2;if (Heap[p] <= x) break;//put father's node Drop to heap[i] = heap[p];//current node update i = P;} Heap[i] = x;} int priority_q::p op () {int ret = heap[0];//root, min int x = Heap[--sz];//Last node, place the value of the root int i = 0;//Exchange from the root while (i * 2 + 1< SZ) {int a= i * 2 + 1, b= I * 2 + 2;//Two son's position if (b < sz && heap[b]< heap[a]) a = B;//Select the youngest son if (Heap[a] &G t;= x) break; If there is no reversal of size exit//Put the son's value up heap[i] = Heap[a];i = A;} Heap[i] = x; Finally in the found position I fill in x;return ret; }int Main () {priority_q Pq;pq.push (5);p Q.push (Ten);p Q.push (7);p Q.push (2); int size = Pq.size (); for (int i = 0; i < size; i+ +) {cout<< "No." <<i+1<< "number" <<pq.pop () <<endl;} return 0;}
Funny is, after I knocked the above code to run, 360 said this is a Trojan! Make me turn off 360 antivirus to run successfully
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Push,pop array Implementation of the heap (Challenge Program design Contest)