堆的创建

#include<stdio.h>
#include<vector>
#include<assert.h>
using namespace std;
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* arry,size_t size)
	{
		_heap.reserve(size);
		for(int i=0;i<size;i++)
		{

			_heap.push_back(arry[i]); 
		} 
		int _size=_heap.size();
		for(int root=(_size-2)/2;root>=0;--root)
		{
			AdjustDown(root);
		}
	}
	void Push(const T&value)
	{
		_heap.push_back(value);
		AdjustUp(_heap.size()-1);
	}
	void Pop()
	{
		assert(!_heap.empty());
		swap(_heap[0],_heap[_heap.size()-1]);
		_heap.pop_back();
		AdjustDown(0);
	}
	T& GetTop()
	{
		assert(!_heap.empty());
		return _heap[0];
	}
	size_t Size()
	{
		return _heap.size();
	}
private:
	void AdjustDown(size_t root)
	{
		assert(!_heap.empty());
		int parent=root;
		int child=parent*2+1;
		int size=_heap.size();
		while(child<size)
		{
			if((child+1<size)&&Compare()(_heap[child],_heap[child+1]))
				child=child+1;
		   if(Compare()(_heap[child],_heap[parent]))
			{
				swap(_heap[child],_heap[parent]);
				parent=child;
				child=2*parent+1;
			}
			else
				return; 
		}
	}
	void AdjustUp(size_t root)
	{
		assert(!_heap.empty());
		int size=_heap.size();
		int child=root;
		int parent=(child-1)>>1;
		while(parent>0)
		{
				if(Compare()(_heap[parent],_heap[child]))
				{
					swap(_heap[parent],_heap[child]);
					child=parent;
					parent=(child-1)>>1;
				}
			else
				return ;
		}
	}
	vector<T> _heap;
};
void TestHeap()
{
	int arry[]={10,11,98,56,16,18,15,17,14,19};
	Heap<int> hp1(arry,sizeof(arry)/sizeof(arry[0]));
	hp1.Push(34);
	hp1.Pop();
}
int main()
{
	TestHeap();
	system("pause");
	return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值