堆与优先级队列实现

时间:2022-08-22 10:14:33
#include<iostream>
using namespace std;
#include <vector>
#include<assert.h>

template<class T>
struct Less
{
	bool operator()(const T& left,const T& right)
	{
		return left<right;
	}
};
template<class T>
struct Greater
{
	bool operator()(const T& left,const T& right)
	{
		return left>right;
	}
};
template<class T,class Compare=Less<T>>
class Heap
{
public:
	// 创建一个空堆
	Heap()
	{}

	Heap(const T array[], size_t size)
	{
		_heap.resize(size);
		for(size_t idx=0;idx<size;idx++)
		{
			_heap[idx]=array[idx];
		}
		int root=(_heap.size()-2)>>1;
		for(;root>=0;root--)
		{
			_AdjustDown(root);
		}
	}
	size_t Size()const
	{
		return _heap.size();
	}
	const T& Top()const
	{
		assert(!_heap.empty());
		return _heap[0];
	}
	bool Empty()const
	{
		return _heap.empty();
	}
	void Insert(const T& data)
	{
		_heap.push_back(data);
		if(_heap.size()>1)
		{
			_AdjustUp();
		}
	}
	void Remove()
	{
		assert(!_heap.empty());
		if(_heap.size()>1)
		{
			std::swap(_heap[0],_heap[_heap.size()-1]);
			_heap.pop_back();
			_AdjustDown(0);
		}
	}

protected:
	void _AdjustDown(size_t parent)
	{
		size_t child=parent*2+1;
		while(child<_heap.size())
		{
			Compare com;
			if(child+1<_heap.size()&&com(_heap[child+1],_heap[child]))
				child+=1;
			if(com(_heap[child],_heap[parent]))
			{
				std::swap(_heap[parent],_heap[child]);
				parent=child;
				child=parent*2+1;
			}
			else
				return;
		}
	}
	void _AdjustUp()
	{
		size_t child=_heap.size()-1;
		size_t parent=(child-1)>>1;
		while(child!=0)
		{
			if(Compare()(_heap[child],_heap[parent]))
			{
				std::swap(_heap[child],_heap[parent]);
				child=parent;
				parent=(child-1)>>1;
			}
			else
				return;
		}
	}
protected:
	std::vector<T> _heap;
};




/////优先级队列
template<class T, class Compare = Less<T>>
class PriorityQueue
{
public:
	PriorityQueue()
	{}
	void Push(const T& data)
	{
		_hp.Insert(data);
	}
	void Pop()
	{
		_hp.Remove();
	}
	const T& Top()const
	{
		return _hp.Top();
	}
	size_t Size()const
	{
		return _hp.Size();
	}
	bool Empty()const
	{
		return _hp.Empty();
	}
protected:
	Heap<T, Compare> _hp;
};
int main()
{
	int arr[]={53,17,78,9,45,65,87,23};
	Heap<int,Greater<int>> s(arr,8);
	return 0;
}