在建立最小堆或最大堆时。最主要的就是理解。SiftDown和SiftUp算法的实现问题。其实我觉得自己在画一棵树。先比较左右再比较父点之间。是最大堆往上。最小堆往下。就很能理解了,
下面程序是最小堆。
#include <iostream>
using namespace std;
template<class Elem>
class MinHeap
{
private:
Elem* heapArray;
int CurrentSize;
int MaxSize;
public:
MinHeap(const int n);
virtual~ MinHeap()
{
delete []heapArray;
}
void BuildHeap();
bool isLeaf(int pos) const;
int leftChild(int pos) const;
int rightChild(int pos) const;
//return parent position
int parent(int pos) const;
//删除给定下标的元素。
bool Remove(int pos,Elem& node);
void SiftDown(int left);
void SiftUp(int position);
bool Insert(const Elem& newNode);
Elem& RemoveMin();
bool print() const;
};
template<class Elem>
MinHeap<Elem>::MinHeap(const int n)
{
i