首页 > 学院 > 开发设计 > 正文

数据结构-堆(Heap)

2019-11-06 06:22:27
字体:
来源:转载
供稿:网友
#include <iostream>#include <vector>using namespace std;template<typename T>   //仿函数,用来控制大堆小堆struct Bigger{	bool Operator()(T left, T right)	{		return left > right;	}};template<typename T>struct Lower{	bool operator()(T left, T right)	{		return left < right;	}};template<typename T, typename Compare = Bigger<T>>class Heap{public:	Heap(){}	Heap(T* a, size_t size)		:_a(a, a + size)	{		for (int i = (_a.size() - 2) / 2; i >= 0; --i)		{			_AdjustDown(i);		}	}	void Push(const T& x)	{		_a.push_back(x);		_AdjustUp(_a.size() - 1);	}	void Pop()	{		if (_a.size() == 0)			return;		swap(_a[0], _a[_a.size() - 1]);		_a.pop_back();		_AdjustDown(0);	}PRotected:	void _AdjustDown(size_t index)  	{		size_t parent = index;		size_t child = parent * 2 + 1;		while (child < _a.size())		{			if (child + 1<_a.size() && Compare()(_a[child + 1], _a[child]))			{				++child;			}			if (Compare()(_a[child], _a[parent]))			{				swap(_a[parent], _a[child]);				parent = child;				child = parent * 2 + 1;			}			else			{				break;			}		}	}	void _AdjustUp(size_t index)  	{		size_t child = index;		size_t parent = (child - 1) / 2;		while (child > 0)		{			if (Compare()(_a[child], _a[parent]))			{				swap(_a[parent], _a[child]);				child = parent;				parent = (child - 1) / 2;			}			else			{				break;			}		}	}protected:	vector<T> _a;};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表