堆排序, 一種基礎算法, 實現了一個二叉樹, 根節點的值大於子節點, 就是最大堆。 小於子節點, 就是最小堆。 堆排序的性能是O(nlg(n)). 插入, 取值都是O(lg(n)). 優先級隊列經常用堆排序來實現。 以下是我的實現:
inline int heapLeft(int i) {return 2 * i + 1;}
inline int heapRight(int i) {return 2 * i + 2;}
inline int heapParent(int i) {return (i - 1) / 2;}
用來取得子女和父母的下標。
template<class Iter, class Function>
void maxHeapify(Iter first, int length, int index, Function f)
{
int largest = index;
int l = heapLeft(index);
int r = heapRight(index);
if (l < length && f(*(first + l) , *(first + largest)))
{
largest = l;
}
if (r < length && f(*(first + r) , *(first + largest)))
{
largest = r;
}
if (largest != index)
{
std::swap(*(first + largest), *(first + index));
maxHeapify(first, length, largest, f);
}
}
維持堆的特性。
template<class Iter, class Function>
void buildHeap(Iter first, Iter last, Function f)
{
for (int i = (last - first) / 2; i >= 0; --i)
{
maxHeapify(first, last - first, i, f);
}
}
生成堆函數。
template<class _RandomAccessIterator, class Function>
void heapSort(_RandomAccessIterator first, _RandomAccessIterator last, Function f)
{
buildHeap(first, last, f);
size_t length = last - first;
for (int i = length - 1; i > 0; --i)
{
std::swap(*(first + i), *first);
--length;
maxHeapify(first, length, 0, f);
}
}
堆排序算法。
還利用堆的函數實現了一個優先級隊列, vector是隊列的容器。 傳入一個堆比較函數。 實現如下:
template<class _Ty, class Function>
class PriorityQueue
{
public:
template<class Iter>
PriorityQueue(Iter first, Iter last)
{
assign(first, last);
}
PriorityQueue()
{
}
template<class Iter>
void assign(Iter first, Iter last)
{
for (Iter it = first; it != last; ++it)
{
m_data.push_back(*it);
}
buildHeap(m_data.begin(), m_data.end(), m_function);
}
inline _Ty top()
{
return m_data[0];
}
inline size_t size() {return m_data.size();}
_Ty extract()
{
if (m_data.empty())
{
return _Ty();
}
_Ty _result = top();
std::swap(m_data[0], m_data[m_data.size() - 1]);
m_data.pop_back();
maxHeapify(m_data.begin(), m_data.size(), 0, m_function);
return _result;
}
void increaseKey(int index, const _Ty& addValue)
{
if (index < m_data.size())
{
m_data[index] += addValue;
}
bottomMaxHeapify(index);
}
void insert(const _Ty& value)
{
m_data.push_back(value);
bottomMaxHeapify(m_data.size() - 1);
}
private:
void bottomMaxHeapify(int index)
{
while (index > 0 && m_function(m_data[index], m_data[heapParent(index)]))
{
std::swap(m_data[heapParent(index)], m_data[index]);
index = heapParent(index);
}
}
private:
std::vector<_Ty> m_data;
Function m_function;
};