大小堆实现

#include <iostream>
#include <vector>
#include <windows.h>
#include <assert.h>
using namespace std;


template <class T>

class Heap
{
protected:
	vector<T> _a;      //一维数组

	//void _AdjustDown(int root)     //下调,构建大堆
	//{
	//	int parent = root;
	//	int child = parent * 2 + 1;    //左孩子

	//	while (child < _a.size())
	//	{
	//		if ((child + 1) < _a.size() && _a[child] < _a[child + 1])
	//		{
	//			child++;
	//		}

	//		if (_a[child]>_a[parent])
	//		{
	//			swap(_a[child], _a[parent]);
	//			parent = child;
	//			child = parent * 2 + 1;
	//		}
	//		else
	//		{
	//			break;
	//		}
	//	}
	//}


	void _AdjustDown(int root)     //下调,构建小堆
	{
		int parent = root;
		int child = parent * 2 + 1;    //左孩子

		while (child < _a.size())
		{
			if ((child + 1) < _a.size() && _a[child] > _a[child + 1])
			{
				child++;
			}

			if (_a[child]<_a[parent])
			{
				swap(_a[child], _a[parent]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
			{
				break;
			}
		}
	}

public:
	Heap()
	{}

	Heap(T* a, size_t n)      //创建堆
	{
		_a.reserve(n);        //开辟空间,reserve不初始化,赋值一次
		//_a.resize(n);    先初始化为默认值,在一次拷贝值,赋值两次
		for (size_t i = 0; i < n; ++i)
		{
			_a.push_back(a[i]);
			//_a[i]=a[i];
		}
		for (int j = (_a.size() - 2) / 2; j >= 0; --j)
		{
			_AdjustDown(j);
		}
		
	}


	void Push(const T& x)        //插入
	{
		_a.push_back(x);
		AdjustDown();
	}

	
	void Pop()   //删除
	{
		assert(!_a.empty());
		swap(_a[0], _a[_a.size() - 1]);
		_a.pop_back();
		AdjustDown();
	}


	const T&  Top() const   //堆顶
	{
		return _a[0];
	}

	void AdjustDown()     //下调,构建小堆
	{
		for (int j = (_a.size() - 2) / 2; j >= 0; --j)
		{
			_AdjustDown(j);
		}
	}

	void Print()
	{
		for (size_t i = 0; i < _a.size(); ++i)
		{
			cout << _a[i] << "->";
		}
		cout << endl;
	}

};



#include "heap.h"
void test()
{
	int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
	Heap<int>  pp(a, sizeof(a) / sizeof(a[0]));
	pp.Print();
	pp.Push(100);
	pp.Print();
	cout << pp.Top() << endl;
	pp.Pop();
	pp.Print();
}

int main()
{
	test();
	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值