实用类之二-----最大堆的实现

本文介绍了一个最大堆的数据结构实现,包括插入、删除最大元素等核心操作,并通过示例展示了其基本用法。最大堆作为优先队列的基础,在算法设计中有着广泛的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最小(大)堆是比较常用的数据结构,是实现优先队列和堆排序的基础,也可以实现例如霍夫曼编码,贪心算法等,具有很好的时间复杂性.
[code]
template<class T>
class MaxHeap{
public:
MaxHeap(T a[],int n);
MaxHeap(int ms);
~MaxHeap();
bool Insert(const T &x);//插入一个元素,如果空返回false,否则返回true
bool RemoveMax(T &x);//删除最小的元素,如果空返回false,否则返回true
void MakeEmpty();//使堆为空
bool IsEmpty();
bool IsFull();

protected:
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>
MaxHeap<T>::MaxHeap(int ms):defaultSize(100){
maxSize = ms > defaultSize ? ms : defaultSize;
heap = new T[maxSize];
currentSize = 0;
}
template<class T>
MaxHeap<T>::MaxHeap(T a[],int n):defaultSize(100){
maxSize = n > defaultSize ? n : defaultSize;
heap = new T[maxSize];
currentSize = n;
for(int i = 0; i < n; i++)
heap[i] = a[i];
int curPos = (currentSize - 2) / 2;
while(curPos >= 0){
FilterDown(curPos,currentSize - 1);
curPos--;
}
}
template<class T>
MaxHeap<T>::~MaxHeap(){
delete []heap;
}
template<class T>
void MaxHeap<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 MaxHeap<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 MaxHeap<T>::RemoveMax(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 MaxHeap<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 MaxHeap<T>::IsEmpty(){
return currentSize == 0;
}

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

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

MainApp.cpp测试文件:

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

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

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

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

[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值