数据结构与算法_堆

满二叉树中如果子节点的位置是n(位置从0开始),那么他的父节点的位置是(n-1)/2
在这里插入图片描述MaxHeap.h

#pragma once

#include <iostream>
//using namespace std;

template<class T>
class MaxHeap
{
public:
	MaxHeap(int mx=10);
	~MaxHeap();
	
	bool IsEmpty();
	void Push(const T&);
	void Pop();
	const T& Top() const;
private:
	T* heapArray;
	int maxSize; 
	int curSize;
	
	void trickleUp(int index);	//向上冒泡
	void trickleDown(int index);	//向下冒泡	
};

template<class T>
MaxHeap<T>::MaxHeap(int mx)
{
	if(mx < 1)
		throw "max size must be > 1";
	this->maxSize = mx;
	this->curSize = 0;
	this->heapArray = new T[maxSize];
}

template<class T>
bool MaxHeap<T>::IsEmpty()
{
	return (curSize == 0);
}
template<class T>
void MaxHeap<T>::Push(const T& data)
{
	if(curSize == maxSize)
		throw "MaxHeap is full";
	heapArray[curSize] = data;
	trickleUp(curSize);	//向上冒泡,找到合适的位置 
	curSize++; 
}
template<class T>
void MaxHeap<T>::Pop()
{
	heapArray[0] = heapArray[--curSize];	//一定要--,因为是下标
	trickleDown(0); 		//从根开始向下渗透 
	
}

template<class T>
MaxHeap<T>::~MaxHeap()
{
	delete[] heapArray;
}
template<class T>
void MaxHeap<T>::trickleUp(int index)	//向上冒泡
{
	int parent = (index - 1)/2;
	T temp = heapArray[index];
	while(index > 0 && heapArray[parent] < temp)
	{
		heapArray[index] = heapArray[parent]; 
		index = parent;
		parent = (parent - 1) / 2;	//不断向上 
	}
	heapArray[index] = temp;	//插入位置 
}
template<class T>
void MaxHeap<T>::trickleDown(int index)	//向下冒泡
{
	T top = heapArray[index];	//保存临时的根  
	int leftChild = 0; 
	int rightChild = 0;
	int largerChild = 0;
	
	while(index < curSize/2)	//到最后一层的上一层,就可以操作他的子节点 
	{
		leftChild = 2 * index + 1;
		rightChild = leftChild + 1;		//从0开始的下标
		
		//rightChild < curSize 是判断最后一个父节点有左右两个节点,还是只有一个左节点 
		if(rightChild < curSize && heapArray[leftChild] < heapArray[rightChild])
			largerChild = rightChild;
		else	//只有一个左节点或者左节点的数大 
			largerChild = leftChild;
		
		if(top >= heapArray[largerChild])	//找到位置
			break;
		else
		{
			heapArray[index] = heapArray[largerChild]; 
			index = largerChild;	//继续向下渗透 
		}
	}
	heapArray[index] = top;	 
}

template<class T>
const T& MaxHeap<T>::Top() const
{
	return heapArray[0];
}	

main.h

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


int main() 
{
	MaxHeap<int> heap(100);
	cout << heap.IsEmpty() << endl;
	
	heap.Push(20);
	heap.Push(30);
	heap.Push(15);
	
	cout << "最大值是: " << heap.Top() << endl;
	heap.Push(90);
	cout << "最大值是: " << heap.Top() << endl;
	heap.Pop();
	cout << "最大值是: " << heap.Top() << endl;
	return 0;
}

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值