您的位置:首页 > 其它

算法导论: 第六章 堆排序算法

2007-01-15 11:16 232 查看
堆排序, 一种基础算法, 实现了一个二叉树, 根节点的值大于子节点, 就是最大堆。 小于子节点, 就是最小堆。 堆排序的性能是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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: