此处的堆,是一棵完全二叉树。

.h

class Heap
{
	public:
		Heap(int capacity = 20);
		~Heap();
		
		bool IsFull() const;
		bool IsEmpty() const;
		int  GetMin() const;
		int  Delete();
		void Insert(int);

	private:
		int  _capacity;
		int  _size;
		int *_heap; 
		
		void _SiftUp();
		void _SiftDown();
		void _Swap(int, int);
};

.cpp

Heap::Heap(int capacity)
{
	_capacity = capacity;
	_size     = 0;
	
	_heap = new int[_capacity + 1];
}


Heap::~Heap()
{
	delete [] _heap;
}

bool Heap::IsFull() const
{
	return _size == _capacity;
}

bool Heap::IsEmpty() const
{
	return _size == 0;
}

int Heap::GetMin() const
{
	return _heap[1];
}

void Heap::_SiftUp()
{
	int sonPos    = _size;
	int parentPos = -1;
	while(true)
	{
		if(sonPos == 1)
			break;
		
		parentPos = sonPos / 2;
		
		if(_heap[parentPos] <= _heap[sonPos])
			break;
		
		_Swap(parentPos, sonPos);
		sonPos = parentPos;
	}
}

void Heap::_SiftDown()
{	
	int parentPos = 1;
	int sonPos    = -1;
	while(true)
	{
		sonPos = parentPos * 2;
		if(sonPos > _size)
			break;

		if(sonPos + 1 <= _size)
			if(_heap[sonPos] > _heap[sonPos + 1])
				sonPos++;
		
		if(_heap[parentPos] <= _heap[sonPos])
			break;

		_Swap(parentPos, sonPos);
		parentPos = sonPos;
	}
}

void Heap::_Swap(int i, int j)
{
	int tmp  = _heap[i];
	_heap[i] = _heap[j];
	_heap[j] = tmp;
}

int Heap::Delete()
{
	int top = _heap[1];
	
	_Swap(1, _size);
	_size -= 1;
	_SiftDown();
	
	return top;
}
		
void Heap::Insert(int data)
{
	_heap[++_size] = data;
	_SiftUp();	
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值