2007-04-09
实用类之一-----最小堆的实现
最小(大)堆是比较常用的数据结构,是实现优先队列和堆排序的基础,也可以实现例如霍夫曼编码,贪心算法等,具有很好的时间复杂性.
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;
}
- 23:21
- 浏览 (1330)
- 评论 (4)
- 分类: Data Structure
- 进入论坛
- 相关推荐
- 浏览: 71858 次
- 性别:

- 来自: 长春

- 详细资料
搜索本博客
我的相册
spy
共 7 张
共 7 张
最近加入圈子
链接
最新评论
-
明天回家,也盘点一下这学 ...
貌似很充实的。。。向你学习。。
-- by wangshu3000 -
学SSH2时写的入门例子
谢谢,楼主是大好人啊!
-- by zzqLivecn -
对以前扫雷游戏功能进一步 ...
这是我大二的时候写的,代码写的比较烂
-- by fuliang -
对以前扫雷游戏功能进一步 ...
希望你继续完善,不能一边写着那些模式和原则,一边写着这样的代码哦。过几天我再来看 ...
-- by healer_kx -
放假了,n长时间没有用过c+ ...
其实我想评价你其他的C++文章。
-- by healer_kx






评论排行榜