In this blog, we use C + + to write an algorithm to build a large heap, in which the adjustment after the deletion of the heap elements is top-down, while the creation of the heap adjustment algorithm for bottom-up adjustment.
The Big top heap structure we build is:
After removing the heap top element, the structure of the heap is:
#include <iostream> #include <string> using namespace std;
void swap (int& I, int& j) {int temp;
temp = i;
i = j;
j = temp; int max (int i, int j) {return i > J i:j;} class max_queue{Public:max_queue () {} max_queue (int
n);
void push (int value);
int pop ();
bool Empty ();
bool Full ();
void Show ();
~max_queue ();
private:int* Base;
int cursize;
int capacity;
};
Max_queue::max_queue (int n) {base = new Int[n];
capacity = N;
cursize = 0;
Max_queue::~max_queue () {delete[] base; bool Max_queue::empty () {if (cursize = = 0) {return true;
} else{return false;
BOOL Max_queue::full () {if (cursize = = capacity) return true;
else return false; } void Max_queue::p ush (int value) {if (full ()) {cout <<) the element in the heap is fully loaded and cannot continue to join ...
"<< Endl;
Return
} base[cursize++] = value;
int j = curSize-1; int I, temp;
while (J > 0) {i = (j-1)/2;
if (i >= 0 && base[j] > Base[i]) {swap (BASE[J), base[i]);
j = i;
} else{break;
}} void Max_queue::show () {for (int i = 0; i < cursize; i++) {cout << base[i] << Endl;
{int Max_queue::p op () {int max_top = 0; if (empty ()) {cout << "The heap is empty, the element cannot be deleted ...
"<< Endl;
return-1;
} max_top = base[0];
Base[0] = base[--cursize];
int j = 0;
while (J < cursize) {int lchild = 2 * j + 1;
int rchild = 2 * j + 2; if (Lchild < cursize) {if (Rchild < cursize) {int temp = max (Base[lchild], Base[rchild])
; if (temp > Base[j]) {if (temp = = Base[lchild]) {swap (base[j], Base[lchild])
;
j = lchild;
} else{swap (Base[j], base[rchild]);
j = rchild;
} else{break; } else{if (max (Base[lchild), base[j]) >base[j]) {Swap (bas
E[lchild], base[j]);
} break;
} else{break;
} return max_top;
int main () {Max_queue MQ (10);
Mq.push (10);
Mq.push (100);
Mq.push (20);
Mq.push (200);
Mq.push (18);
Mq.push (50);
Mq.push (300);
cout << "created heap is:" << Endl;
Mq.show ();
cout << "Delete the structure of the heap after the top element of the heap:" << Endl;
Mq.pop ();
Mq.show ();
return 0; }
Run Result: