堆的实现

堆数据结构是一种数组对象,它可以被视为一棵完全二叉树结构。
堆结构的二叉树存储是
最大堆:每个父节点的都大于孩子节点。
最小堆:每个父节点的都小于孩子节点。
                                   
实现代码如下:
#include <iostream>
using namespace std;

#include <vector>
#include<assert.h>

template<class T>
struct Less
{
	bool operator()(const T& l, const T& r)
	{
		return l > r;
	}
};

template<class T>
struct Greater
{
	bool operator()(const T& l, const T& r)
	{
		return l < r;
	}
};



template<class T, class compare = Less<T>>
class Heap{
public:
	Heap()
	{}

	Heap(const int* a, size_t size)
	{
		for (int i = 0; i < size; i++)
		{
			_array.push_back(a[i]);
		}
		int parent = (_array.size() - 2)/2;
		for (; parent >= 0; parent--)
		{
			_AdjustDown(parent);
		}
	}

	int Size()
	{
		return _array.size();
	}

	bool IsEmpty()
	{
		return _array.size() == 0;
	}

	T& Top()
	{
		assert(_array.size());
		return _array[0];
	}

	void Pop()
	{
		if (IsEmpty())
		{
			return;
		}
		swap(_array[0],_array[_array.size() - 1]);
		_array.pop_back();
		_AdjustDown(0);
	}

	void Push(const T& x)
	{
		_array.push_back(x);
		if (_array.size() > 1)
		{
			_AdjustUp(_array.size() - 1);
		}
	}

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

protected:

	void _AdjustUp(int child)
	{
		int parent = (child - 1) / 2;
		while (child > 0)
		{
			if (compare()(_array[parent], _array[child]))
			{
				swap(_array[parent], _array[child]);
				child = parent;
				parent = (child - 1) / 2;
			}
			else
			{
				break;
			}
		}
	}

	void _AdjustDown(int parent)
	{
		int child = parent * 2 + 1;
		compare com;
		while (child < _array.size())
		{
			if ((child+1<_array.size()) && com(_array[child], _array[child+1]))
			{
				child++;
			}
			if (com(_array[parent], _array[child]))
			{
				swap(_array[parent], _array[child]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
			{
				break;
			}
		}
	}
private:
	vector<T> _array;
};

int main()
{
	int a[10] = {10,16,18,12,11,13,15,17,14,19};
	Heap<int> hp(a,10);
	hp.Print();
	hp.Push(5);
	hp.Top();
	hp.Pop();
	hp.Size();
	return 0;
}

堆的应用有:

1.优先级队列

2.100w个数中找出最大的前K个数

3.堆排序



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值