此处的堆,是一棵完全二叉树。
.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();
}