Recently I reviewed the classic heapsort algorithm and implement it according to contents in Introduction to Algorithms (3rd edition). The heap data structure is implemented as a template class and the heapsort algorithm is implemented as a public method of the template class. The code is as follows.

  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. template<typename T> class Heap {
  7. public:
  8. Heap(vector<T>&);
  9. ~Heap(void);
  10.  
  11. inline int parent(int);
  12. inline int left(int);
  13. inline int right(int);
  14.  
  15. void max_heapify(int);
  16. void build_max_heap(void);
  17. void heap_sort(void);
  18.  
  19. /* Methods for maximum priority queue. */
  20. T maximum(void);
  21. T extract_max(void);
  22. void increase_key(int, T);
  23. void insert_key(T);
  24.  
  25. void print(void);
  26. private:
  27. vector<T> data;
  28. int heap_size;
  29. };
  30.  
  31. template<typename T> Heap<T>::Heap(vector<T>& d) {
  32. data = d;
  33. build_max_heap();
  34. }
  35.  
  36. template<typename T> Heap<T>::~Heap(void) {
  37. data.clear();
  38. heap_size = ;
  39. }
  40.  
  41. template<typename T> inline int Heap<T>::parent(int idx) {
  42. return (idx - ) >> ;
  43. }
  44.  
  45. template<typename T> inline int Heap<T>::left(int idx) {
  46. return (idx << ) + ;
  47. }
  48.  
  49. template<typename T> inline int Heap<T>::right(int idx) {
  50. return (idx << ) + ;
  51. }
  52.  
  53. template<typename T> void Heap<T>::max_heapify(int idx) {
  54. int largest = idx;
  55. int l = left(idx);
  56. int r = right(idx);
  57. if (l < heap_size && data[l] > data[largest]) largest = l;
  58. if (r < heap_size && data[r] > data[largest]) largest = r;
  59. if (largest != idx) {
  60. swap(data[idx], data[largest]);
  61. max_heapify(largest);
  62. }
  63. }
  64.  
  65. template<typename T> void Heap<T>::build_max_heap(void) {
  66. heap_size = data.size();
  67. for (int i = (heap_size >> 1) - ; i >= ; i--)
  68. max_heapify(i);
  69. }
  70.  
  71. template<typename T> void Heap<T>::heap_sort(void) {
  72. int size = heap_size - ;
  73. for (int i = size; i > ; i--) {
  74. swap(data[i], data[]);
  75. heap_size--;
  76. max_heapify();
  77. }
  78. }
  79.  
  80. template<typename T> T Heap<T>::maximum(void) {
  81. return data[];
  82. }
  83.  
  84. template<typename T> T Heap<T>::extract_max(void) {
  85. if (data.empty()) throw runtime_error("Heap underflow!");
  86. int maximum = data[];
  87. swap(data[], data[heap_size - ]);
  88. heap_size--;
  89. max_heapify();
  90. return maximum;
  91. }
  92.  
  93. template<typename T> void Heap<T>::increase_key(int idx, T key) {
  94. if (key < data[idx]) {
  95. cerr << "New key is smaller!" << endl;
  96. return;
  97. }
  98. data[idx] = key;
  99. while (idx >= 0 && parent(idx) >= 0 && data[parent(idx)] < data[idx]) {
  100. swap(data[idx], data[parent(idx)]);
  101. idx = parent(idx);
  102. }
  103. }
  104.  
  105. template<typename T> void Heap<T>::insert_key(T key) {
  106. data.insert(data.begin() + heap_size, key - );
  107. heap_size++;
  108. increase_key(heap_size - , key);
  109. }
  110.  
  111. template<typename T> void Heap<T>::print(void) {
  112. printf("In heap: ");
  113. for (int i = ; i < heap_size; i++)
  114. printf("%d ", data[i]);
  115. printf(", ");
  116. if (heap_size < (int)data.size()) {
  117. printf("Out of heap: ");
  118. for (int i = heap_size; i < (int)data.size(); i++)
  119. printf("%d ", data[i]);
  120. }
  121. printf("\n");
  122. }
  123.  
  124. void heap_test(void) {
  125. int num[] = {, , , , , , , , , };
  126. vector<int> nums(num, num + sizeof(num) / sizeof(int));
  127. // Construct a heap and print it
  128. Heap<int> heap(nums);
  129. heap.print();
  130. // Test maximum() and extract_max()
  131. printf("%d\n", heap.maximum());
  132. printf("%d\n", heap.extract_max());
  133. heap.print();
  134. // Test increase_key()
  135. heap.increase_key(, );
  136. heap.print();
  137. // Test insert_key()
  138. heap.insert_key();
  139. heap.print();
  140. // Test heap_sort()
  141. heap.heap_sort();
  142. heap.print();
  143. }
  144.  
  145. int main(void) {
  146. heap_test();
  147. system("pause");
  148. return ;
  149. }

If you run this code, the expected output is  like (I am testing it in Microsoft Visual Studio Professional 2012):

  1. In heap: ,
  2.  
  3. In heap: , Out of heap:
  4. In heap: , Out of heap:
  5. In heap: , Out of heap:
  6. In heap: , Out of heap:

Welcome for any question, comment and suggestion about the code!

[Algorithms] Heap and Heapsort的更多相关文章

  1. Heap Sorting 总结 (C++)

    各位读者,大家好. 因为算法和数据结构相关的知识都是在国外学的,所以有些词汇翻译的可能不准确,然后一些源代码的注释可能是英文的,如有给大家带来什么不方便,请见谅.今天我想写一下Heap相关的知识,从基 ...

  2. 排序算法(5)--Selection Sorting--选择排序[2]--Heap Sort--堆排序

    1.基本思想 具有n个元素的序列 (h1,h2,...,hn),当且仅当满足(hi>=h2i,hi>=2i+1)或(hi<=h2i,hi<=2i+1) (i=1,2,...,n ...

  3. 算法 Heap sort

    // ------------------------------------------------------------------------------------------------- ...

  4. David MacKay:用信息论解释 '快速排序'、'堆排序' 本质与差异

    这篇文章是David MacKay利用信息论,来对快排.堆排的本质差异导致的性能差异进行的比较. 信息论是非常强大的,它并不只是一个用来分析理论最优决策的工具. 从信息论的角度来分析算法效率是一件很有 ...

  5. [151225] Python3 实现最大堆、堆排序,解决TopK问题

    参考资料: 1.算法导论,第6章,堆排序 堆排序学习笔记及堆排序算法的python实现 - 51CTO博客 堆排序 Heap Sort - cnblogs 小根堆实现优先队列:Python实现 -cn ...

  6. C语言排序

    排序算法 快速排序 C语言快速排序qsort(数组,长度,元素大小,cmp函数(*,*))//注意函数cmp的参数为指针 #include <stdio.h> #include <s ...

  7. Java与算法之(8) - 堆排序

    堆是一种特殊的完全二叉树,其特点是所有父节点都比子节点要小,或者所有父节点都比字节点要大.前一种称为最小堆,后一种称为最大堆. 比如下面这两个: 那么这个特性有什么作用?既然题目是堆排序,那么肯定能用 ...

  8. 洛谷 P1177 【模板】快速排序【13种排序模版】

    P1177 [模板]快速排序 题目描述 利用快速排序算法将读入的N个数从小到大排序后输出. 快速排序是信息学竞赛的必备算法之一.对于快速排序不是很了解的同学可以自行上网查询相关资料,掌握后独立完成.( ...

  9. 排序算法(Java实现)

    这几天一直在看严蔚敏老师的那本<数据结构>那本书.之前第一次学懵懵逼逼,当再次看的时候,发觉写的是非常详细,非常的好. 那就把相关的排序算法用我熟悉的Java语言记录下来了.以下排序算法是 ...

随机推荐

  1. java基础讲解04-----数据类型和运算符

    1.java的基本数据类型 1.数值型  { 整数型   byte  , short  ,int  ,long 浮点型   float , double } 2.字符型 3.布尔型 2.运算符 1.赋 ...

  2. 数据库表syscolumns 各个字段含义 select * from syscolumns where name='textA'

    每个数据库创建后都会有一些系统表用来存储该数据库的一些基本信息 每个表和视图中的每列在表中占一行,存储过程中的每个参数在表中也占一行.该表位于每个数据库中. 列名 数据类型 描述 name sysna ...

  3. NFS介绍

    一.NFS服务介绍 NFS是 Network File system的缩写 NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机 ...

  4. atitit.js的 字符串内容 转义  js处理html

    atitit.js的 字符串内容 转义  js处理html 1. js处理html的问题 1 2. js的 字符串内容 转义 1 2.1. 处理流程 1 3. 下面的表格列出了其余的特殊字符,这些特殊 ...

  5. MySQL触发器更新本表数据异常:Can't update table 'tbl' in stored function/trigger because it

    MySQL触发器更新本表数据异常:Can't update table 'tbl' in stored function/trigger because it 博客分类: 数据库 MySQLJava ...

  6. iOS开发 -李洪强-清除缓存

    // //  SetViewController.m //  dfhx // //  Created by dfhx_iMac_001 on 16/4/5. //  Copyright © 2016年 ...

  7. myeclipce怎么破解

    MyEclipse安装文件下载,下载地址 http://www.jb51.net/softs/150886.html 你也可以进入官方网站下载:http://www.myeclipsecn.com/d ...

  8. 循环节计算---用到find函数

    #include <iostream> #include <algorithm> #include <vector> using namespace std; in ...

  9. 从浏览器输入URL回车发生了什么

    在浏览器输入url后回车,整个过程发生了什么?整个过程如果节节细述的话,那非常的复杂.我就简单的描述一下整个过程 1.查询DNS,获取域名对应的IP地址 (1).浏览器搜索自身的DNS缓存 (2).搜 ...

  10. Quotations中页面弹出的问题