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

     堆排序, 一种基础算法,  实现了一个二叉树, 根节点的值大于子节点, 就是最大堆。 小于子节点, 就是最小堆。 堆排序的性能是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;
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值