数据结构--------最大堆最小堆

#include <iostream>
#include <cassert>
using namespace std;
const int DefaultSize = 1;
//最小堆有线性表的结构
//有头,顺序存储有搜索便捷的优点,直接根据下标。
template <class T ,class E> 
class MinHeap
{// T为关键码的数据类型,E为记录的结构类型
public:
	MinHeap(int sz)//构造函数:建立空堆
	{
		maxHeapSize = (DefaultSize < sz) ? sz:DefaultSize;
		heap = new E[maxHeapSize+1];
		if (heap == NULL) { cerr << "堆分配失败!" << endl; exit(1); }
		currentSize = 0;
	}
	MinHeap(E arr[], int n)	//构造函数:通过一个数组建堆
	{
		maxHeapSize = (DefaultSize < n) ? n: DefaultSize;
		heap = new E[maxHeapSize+1];
		if(heap==NULL) { cerr << "堆分配失败!" << endl; exit(1); }
		for (int i = 0; i < n; i++)   heap[i] = arr[i];//给堆赋值
		currentSize = n;
		int currentPos = (currentSize - 2) / 2;
		while (currentPos >= 0)
		{
			siftDown(currentPos, currentSize - 1);
			currentPos--;
		}
	}
	~MinHeap() {
		delete[]heap;
	}
	bool Insert(const E& x)//在最小堆里插入一个结点
	{
		heap[currentSize] = x; //把数据先放入其中
		siftUp(currentSize);
		currentSize++;
		return true;
	}
	bool RemoveMin(E& x)
	{
		if (currentSize == 0) return false;
		x = heap[0];
		heap[0] = heap[currentSize - 1];
		currentSize--;
		siftDown(0, currentSize - 1);
		return true;
	}
	bool IsEmpty()const {
		return currentSize == 0;
	}
	bool IsFull()const {
		return currentSize == maxHeapSize;
	}
	void MakeEmpty() {
		delete heap;
		currentSize = 0;
	}
	void output() {//自定义函数,顺序输出最小堆元素	
		for (int i = 0; i < currentSize; i++)
			cout << heap[i] << " ";
		cout << endl;
	}
private:
	E * heap;						    //存放最小堆中元素的数组
	int currentSize;				   //最小堆中当前元素个数
	int maxHeapSize;				  //最小堆最多允许元素个数
	void siftDown(int start, int m)   //从start到m下滑调整成为最小堆
	{
		int i = start,j=2*i+1;  //i 从根开始,j 是左结点
		T temp = heap[i];  //先把值保存起来  看后面比较要不要做交换
		while (j <= m)//在堆的范围内
		{
			//找子女中较小者
			if (j<m && heap[j]>heap[j + 1])
			{
				j++;
			}
			if (temp <= heap[j]) break;
			else
			{
				heap[i] = heap[j]; //给heap[i]较小值的值
				i = j;
				j = 2 * j + 1;
			}
		}
		heap[i] = temp;
	}
	void siftUp(int start)		//从start到0上滑调整成为最小堆
	{
		int j = start,i=(j-1)/2;
		T temp=heap[j];
		while (j > 0)
		{
			if (heap[i] <= temp) break;
			else
			{
				heap[j] = heap[i];
				j = i;
				i = (i - 1) / 2;
			}
			
		}
		heap[j] = temp;
	}
};




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

int main()
{
	int a[5] = { 5,3,7,1,32 };
	int x = 0;
	MinHeap<int,int> mheap(a,5);
	mheap.output();
	mheap.Insert(2);
	mheap.RemoveMin(x);
	cout <<"最小值:  "<< x<<endl;
	mheap.output();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值