标签:
/*
*date : 2015-07-28
*description: MaxHeap.h
*/
#ifndef _MAX_HEAP_H
#define _MAX_HEAP_H
template<class T>
class MaxHeap{
public:
MaxHeap(int MaxHeapSize = 10);
~MaxHeap() {delete [] heap;}
int Size() const {return CurrentSize;}
T Max()
{
if(CurrentSize == 0)
throw out_of_range("堆为空!");
return heap[1];
}
MaxHeap<T>& Insert(const T& x);
MaxHeap<T>& Delete(T& x);
//void Initialize(T a[], int size, int ArraySize); // 将一个数组初始化为大根堆
private:
int CurrentSize;
int MaxSize;
T *heap;
};
#include "MaxHeap.cpp"
#endif//_MAX_HEAP_H
/*
*date : 2015-07-28
*description: MaxHeap.cpp
*/
#ifndef _MAX_HEAP_CPP
#define _MAX_HEAP_CPP
#include "MaxHeap.h"
template<class T>
MaxHeap<T>::MaxHeap(int MaxHeapSize)
{
MaxSize = MaxHeapSize;
heap = new T[MaxSize+1];
CurrentSize = 0;
}
//
template<class T>
MaxHeap<T>& MaxHeap<T>::Insert(const T& x)
{
//把x插入到大根堆中
if(CurrentSize == MaxSize)
throw out_of_range("没有足够空间!");//
//为x寻找应插入位置
//i从新的叶节点开始,并沿着树上升
int i = ++CurrentSize;
while (i != 1 && x > heap[i/2]) // 大于父节点
{
// 不能把x放入heap[i]
heap[i] = heap[i/2]; //父节点下移
i /= 2;
}
heap[i] = x;
return *this;
}
//
template<class T>
MaxHeap<T>& MaxHeap<T>::Delete(T& x)
{
//将最大元素(根)放入x,并从对中删除元素
if(CurrentSize == 0)
throw out_of_range("堆为空!");
x = heap[1]; // 最大元素
// 重构堆
T y = heap[CurrentSize--];// 堆中最后一个元素
//从根节点开始,为y寻找合适的位置
int i = 1; // 当前节点(根节点)
int ci = 2; // i的孩子节点
while (ci <= CurrentSize)
{
if(ci < CurrentSize && heap[ci] < heap[ci+1])
ci++; //heap[ci]是i的较大的孩子节点
if(y >= heap[ci])
break;
heap[i] = heap[ci]; //将孩子节点上移
i = ci;
ci *= 2;
}
heap[i] = y;
return *this;
}
#endif//_MAX_HEAP_CPP
标签:
原文地址:http://www.cnblogs.com/hzwackerman/p/4684285.html