数据结构:堆

博客展示了 C++ 相关内容,包含源代码以及对应的输出结果,聚焦于信息技术领域的 C++ 编程。

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

数据结构:堆

源代码

#include<iostream>
using namespace std;

template<class T>
void Swap(T& a,T&b){
	T temp = a;
	a = b;
	b = temp;
}

template<class T>
class heap{
	public:
	heap(int n=10){
		maxlength = n;
		length = 0;
		arr = new T[n];
	}//初始化大根堆
	~heap(){
		delete []arr;
	}//销毁堆
	void insert(T&);//向大根堆里插入一个元素
	bool empty(){
		return length == 0;
	}//判断堆是否为空
	T& get(){
		if(empty()){
			cout<<"堆为空"<<endl;
		}
		return arr[0];//返回堆顶元素
	}
	void del();//删除堆顶元素
	void output(){
		for(int i=0;i<length;i++)cout<<arr[i]<<" ";
		cout<<endl;
	}//输出堆
	private:
	T * arr;//存放元素的数组
	int length;//当前元素的大小
	int maxlength;//当前数组的最大容量
};

template<class T>
void heap<T>::del(){
	if(empty()){
		cout<<"堆为空"<<endl;
		return ;
	}
	arr[0]=arr[--length];
	int father = 0;
	int child =1;
	while(child<length){
		if(child+1<length&&arr[child]<arr[child+1])child++;
		if(arr[father]>=arr[child])break;
		Swap(arr[father],arr[child]);
		father = child;
		child = (father<<1)+1; 
	}
}

template<class T>
void heap<T>::insert(T& element){
	if(length==maxlength){
		maxlength<<=1;
		T* newArray = new T[maxlength];
		for(int i=0;i<length;i++)newArray[i]=arr[i];
		delete []arr;
		arr = newArray;
	}
	arr[length]=element;
	int child = length;
	int father = (child-1)>>1;
	while(father>=0){
		if(arr[father]>=arr[child])break;
		Swap(arr[father],arr[child]);
		child = father;
		father = (child-1)>>1;
	}
	length++;
}

int main(){
	heap<int> h;
	for(int i=0;i<10;i++)h.insert(i);
	h.output();
	h.del();
	h.output();
}

输出结果

9 8 5 6 7 1 4 0 3 2 
8 7 5 6 2 1 4 0 3 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值