手写堆(大根堆)

#include<iostream>
using namespace std;

//大根堆
class MyHeap{
private:
	int m_heapSize;
	int m_maxSize;
	int * m_arr;

public:
	MyHeap(int limit)
	{
		m_arr = new int[limit];
		this->m_maxSize = limit;
		m_heapSize = 0;
	}

	~MyHeap()
	{
		cout<<"~MyHeap"<<endl;
		delete []m_arr;
		m_arr = nullptr;
	}

	bool isEmpty()
	{
		return this->m_heapSize == 0;
	}

	bool isFull()
	{
		return this->m_heapSize == m_maxSize;
	}

	void push(int val)
	{
		if(isFull())
		{
			cout<<"大根堆已满,无法再push元素"<<endl;
			return;
		}
		m_arr[m_heapSize++]=val;
		heapInsert();
	}

	void swap(int &a, int &b)
	{
		int temp = a;
		a = b;
		b = temp;
	}

	
	//从最后一个位置的元素往上heapInsert
	void heapInsert()
	{
		int index = m_heapSize - 1;
		int fa = (index-1)/2;
		while(m_arr[index] > m_arr[fa])
		{
			swap(m_arr[index], m_arr[fa]);
			index = fa;
			fa = (index-1)/2;
		}
	}

	int pop()
	{
		int val = m_arr[0];
		swap(m_arr[0], m_arr[--m_heapSize]);
		heapify();
		return val;
	}


	//将移上来的最后一个数从0开始往下heapify
	void heapify()
	{
		int index = 0;
		int left = 2*index + 1;
		while(left < m_heapSize)
		{
			//找到左右孩子中较大的那个孩子的坐标
			int maxIndex = left + 1 < m_heapSize && m_arr[left+1] > m_arr[left]? left+1:left;
			if(m_arr[index] > m_arr[maxIndex])
			{
				break;
			}
			swap(m_arr[index], m_arr[maxIndex]);
			index = maxIndex;
			left = 2 * index +1;
		}
	}

	int top()
	{
		if(!this->isEmpty())
		{
			return this->m_arr[0];
		}
		return -1;
	}
};


int main()
{
	MyHeap heap(5);
	heap.push(1);
	cout<<heap.top()<<endl;
	heap.push(3);
	cout<<heap.top()<<endl;
	heap.push(9);
	cout<<heap.top()<<endl;
	heap.push(6);
	cout<<heap.top()<<endl;
	heap.push(3);
	cout<<heap.top()<<endl;
	heap.pop();
	cout<<heap.top()<<endl;
	system("pause");
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值