#include <iostream>
#include <stack>
const int DefaultSize = 100;
template <class T>
class MaxHeap{
public:
MaxHeap(int sz = DefaultSize);
MaxHeap(T arr[], int n);
~MaxHeap(){delete []heap;}
bool Insert(const T &x); // 插入
bool RemoveMin(); // 删除
bool isEmpty()const; // 是否为空
bool isFull()const; // 是否已满
void InOrder(); // 中序遍历完全二叉树
private:
T *heap; // 动态数组存储最小堆
int CurrentSize; // 目前最小堆的结点数
void ShiftDown(int start, int m); // 下滑
void ShiftUp(int start); // 上浮
};
// 构造函数
template <class T>
MaxHeap<T>::MaxHeap(int sz) {
heap = new T[sz]; // 创建堆空间
CurrentSize = 0;
}
// 构造函数
template <class T>
MaxHeap<T>::MaxHeap(T arr[], int n) {
// 为什么求最后非叶要CurrentSize减去2,再除以2,而不是减去1,再除以2
// 因为最后一个数组下标是CurrentSize-1,又因为:左结点j = 2 * i +
// 1,知道j,想求i。可知是:i = (j - 1) / 2;所以,就出现了
// CurrentPos = (CurrentSize - 2) / 2
heap = new T[DefaultSize]; // 创建堆空间
CurrentSize = n; // 当前堆大小
for(int i = 0; i < n; i++)
heap[i] = arr[i];
int CurrentPos = (CurrentSize - 2) / 2; // 最后非叶
while(CurrentPos >= 0) {
// 从下到上逐渐扩大,形成堆
ShiftDown(CurrentPos, CurrentSize-1);
// 到CurrentSize-1为止
CurrentPos--;
}
C++ 最大堆
最新推荐文章于 2025-06-20 09:50:43 发布