堆是一顆被完全填滿的二叉樹,底層的元素從左到右填入。
所以一個高度爲h的堆有2^h到2^(h+1)-1個節點,這樣的堆可以用一個數組來表示,堆頂爲arr[0],父節點的下標爲n,左兒子的下標就是2n+1,
堆有大堆(父節點的值大於兒子節點的值)和小堆(父節點的值小於兒子節點的值),大堆的根節點就是數組中最大的值,小堆的根節點就是數組中最小的值。堆只能訪問根節點,能進行插入和刪除操作。
一共10個元素從第(10-1)/2 = 4開始對每個元素排序一直到排到根節點(第n-1),每個節點的排序按照從上到下的方式如果父節點大於兒子節點中較小的,則交換,否則對下一個元素排序(小堆)
#include <iostream>
using namespace std;
#include <vector>
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 arr[], size_t sz)
{
assert(arr);
for (int i = 0; i < sz; ++i)
_heap.push_back(arr[i]); //用容器存放元素
if (sz > 1)
for (int j = (sz - 1) / 2; j >= 0; --j)
{
_AdjustDown(j);
}
}
size_t Size()const
{
return _heap.size();
}
bool Empty()const
{
return _heap.empty();
}
void Insert(const T& data) //插入
{
_heap.push_back(data);
if (Size() > 1)
_AdjustUp(Size() - 1);
}
void Remove() //刪除堆頂 (交換第一個和最後一個,將最後一個節點刪除,對堆頂向下排序)
{
if (Empty())
return;
if (Size() == 1)
_heap.pop_back();
else
{
std::swap(_heap[0], _heap[Size() - 1]);
_heap.pop_back();
_AdjustDown(0);
}
}
protected:
void _AdjustDown(size_t parent)
{
size_t chlid = 2 * parent + 1;
while (chlid < _heap.size())
{
if (chlid + 1 < _heap.size())
chlid = ( Compare()(_heap[chlid], _heap[chlid+1])) ? chlid : (chlid + 1);
if (Compare()(_heap[parent], _heap[chlid]) )
std::swap(_heap[parent], _heap[chlid]);
parent = chlid;
chlid = 2 * parent + 1;
}
}
void _AdjustUp(size_t chlid)
{
size_t parent = (chlid - 1) / 2;
while (chlid != 0)
{
if ( Compare()(_heap[chlid], _heap[parent]))
std::swap(_heap[chlid], _heap[parent]);
else
break;
chlid = parent;
parent = (chlid - 1) / 2;
}
}
protected:
std::vector<T> _heap;
};
template <class T, class Compare = Less<T>> //用小堆構建優先級隊列
class PriorityQueue {
public:
PriorityQueue()
:_hp()
{}
void Push(const T& data)
{
_hp.Insert(data);
}
void Pop()
{
_hp.Remove();
}
const T& Top()const
{
return _hp._heap[0];
}
size_t Size()const
{
return _hp.Size();
}
bool Empty()const
{
return _hp.Empty();
}
protected:
Heap<T, Compare > _hp;
};