在這篇部落格中,我們利用C++編寫了一個構建大頂堆的演算法,其中,在刪除堆元素之後的調整規為自上而下,而建立堆的時候調整演算法為自下而上調整。
我們構建的大頂堆結構為:
刪除掉堆頂元素之後堆的結構為:
#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::push(int value){ if (full()){ cout << "該堆中元素已滿,無法繼續加入。。。" << 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::pop(){ int max_top = 0; if (empty()){ cout << "該堆為空白,無法刪除元素。。。" << 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(base[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 << "建立的堆為:" << endl; mq.show(); cout << "刪除堆頂元素之後堆的結構:" << endl; mq.pop(); mq.show(); return 0;}
運行結果: