###### 实用类之一-----最小堆的实现

MinHeap.h文件

template<class T>
class MinHeap{
public:
MinHeap(T a[],int n);
MinHeap(int ms);
~MinHeap();
bool Insert(const T &x);//插入一个元素,如果空返回false，否则返回true
bool RemoveMin(T &x);//删除最小的元素，如果空返回false，否则返回true
void MakeEmpty();//使堆为空
bool IsEmpty();
bool IsFull();
void FilterDown(const int start,const int endOfHeap);//自顶向下构造堆
void FilterUp(const int start);//自底向上构造堆
private:
T *heap;
int maxSize;
const int defaultSize;
int currentSize;
};
template<class T>
MinHeap<T>::MinHeap(int ms):defaultSize(100){
maxSize = ms > defaultSize ? ms : defaultSize;
heap = new T[maxSize];
currentSize = 0;
}
template<class T>
MinHeap<T>::MinHeap(T a[],int n):defaultSize(100){
maxSize = n > defaultSize ? n : defaultSize;
heap = new T[maxSize];
currentSize = n;
heap = a;
int curPos = (currentSize - 2) / 2;
while(curPos >= 0){
FilterDown(curPos,currentSize - 1);
curPos--;
}
}
template<class T>
MinHeap<T>::~MinHeap(){
delete []heap;
}
template<class T>
void MinHeap<T>::FilterDown(const int start,const int endOfHeap){
int i = start,j = i * 2 + 1;
T temp = heap[i];
while(j <= endOfHeap){
if(j < endOfHeap && heap[j] > heap[j+1]) j++;
if(temp < heap[j]) break;
else{
heap[i] = heap[j];
i = j;
j = 2 * i + 1;
}
}
heap[i] = temp;
}
template<class T>
void MinHeap<T>::FilterUp(const int start){
int i = start, j = ( i - 1 ) / 2;
T temp = heap[i];
while(i > 0){
if(temp >= heap[j]) break;
else{
heap[i] = heap[j];
i = j;
j = (i - 1) / 2;
}
}
heap[i] = temp;
}
template<class T>
bool MinHeap<T>::RemoveMin(T &x){
if(IsEmpty()){
cerr<<"Heap empty!"<<endl;
return false;
}
x = heap[0];
heap[0] = heap[currentSize - 1];
currentSize--;
FilterDown(0,currentSize-1);
return true;
}
template<class T>
bool MinHeap<T>::Insert(const T& x){
if(IsFull()) {
cerr<<"Heap Full!"<<endl;
return false;
}
heap[currentSize] = x;
FilterUp(currentSize);
currentSize++;
return true;
}
template<class T>
bool MinHeap<T>::IsEmpty(){
return currentSize == 0;
}

template<class T>
bool MinHeap<T>::IsFull(){
return currentSize == maxSize;
}

template<class T>
void MinHeap<T>::MakeEmpty(){
currentSize = 0
}

main.cpp测试文件:

#include<iostream>
#include"MinHeap.h"
using namespace std;

void main(){
int a[5] = {3,2,1,4,5};
MinHeap<int> m_heap(a,5);
int x,i;
for(i = 0; i < 5; i++){
m_heap.RemoveMin(x);
cout << x << " ";
}
cout << endl;

for(i = 0; i < 5; i++){
m_heap.Insert(a[i]);
}

for(i = 0; i < 5; i++){
m_heap.RemoveMin(x);
cout << x << " ";
}
cout << endl;
}

#### 最详细的最小堆构建、插入、删除的过程图解

2016-09-30 17:22:09

#### 【算法】堆，最大堆（大顶堆）及最小堆（小顶堆）的实现

2016-01-07 17:12:24

#### 最小堆的java实现

2014-08-04 10:40:06

#### 最小堆的实现（C 语言版）

2012-08-23 20:09:25

#### 用最小堆实现优先队列

2015-12-02 23:29:49

#### Java最小堆实现

2014-06-02 22:14:26

#### c++实现的最小堆类

2014-07-16 19:55:15

#### 最小堆的实现

2009-12-02 16:36:00

#### 九度oj 题目1172：哈夫曼树(优先队列实现最小堆)

2015-07-02 20:32:55

#### 最大堆与最小堆的实现

2016-03-30 20:57:36