[Algorithms] Heap and Heapsort
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.
#include <iostream>
#include <vector> using namespace std; template<typename T> class Heap {
public:
Heap(vector<T>&);
~Heap(void); inline int parent(int);
inline int left(int);
inline int right(int); void max_heapify(int);
void build_max_heap(void);
void heap_sort(void); /* Methods for maximum priority queue. */
T maximum(void);
T extract_max(void);
void increase_key(int, T);
void insert_key(T); void print(void);
private:
vector<T> data;
int heap_size;
}; template<typename T> Heap<T>::Heap(vector<T>& d) {
data = d;
build_max_heap();
} template<typename T> Heap<T>::~Heap(void) {
data.clear();
heap_size = ;
} template<typename T> inline int Heap<T>::parent(int idx) {
return (idx - ) >> ;
} template<typename T> inline int Heap<T>::left(int idx) {
return (idx << ) + ;
} template<typename T> inline int Heap<T>::right(int idx) {
return (idx << ) + ;
} template<typename T> void Heap<T>::max_heapify(int idx) {
int largest = idx;
int l = left(idx);
int r = right(idx);
if (l < heap_size && data[l] > data[largest]) largest = l;
if (r < heap_size && data[r] > data[largest]) largest = r;
if (largest != idx) {
swap(data[idx], data[largest]);
max_heapify(largest);
}
} template<typename T> void Heap<T>::build_max_heap(void) {
heap_size = data.size();
for (int i = (heap_size >> 1) - ; i >= ; i--)
max_heapify(i);
} template<typename T> void Heap<T>::heap_sort(void) {
int size = heap_size - ;
for (int i = size; i > ; i--) {
swap(data[i], data[]);
heap_size--;
max_heapify();
}
} template<typename T> T Heap<T>::maximum(void) {
return data[];
} template<typename T> T Heap<T>::extract_max(void) {
if (data.empty()) throw runtime_error("Heap underflow!");
int maximum = data[];
swap(data[], data[heap_size - ]);
heap_size--;
max_heapify();
return maximum;
} template<typename T> void Heap<T>::increase_key(int idx, T key) {
if (key < data[idx]) {
cerr << "New key is smaller!" << endl;
return;
}
data[idx] = key;
while (idx >= 0 && parent(idx) >= 0 && data[parent(idx)] < data[idx]) {
swap(data[idx], data[parent(idx)]);
idx = parent(idx);
}
} template<typename T> void Heap<T>::insert_key(T key) {
data.insert(data.begin() + heap_size, key - );
heap_size++;
increase_key(heap_size - , key);
} template<typename T> void Heap<T>::print(void) {
printf("In heap: ");
for (int i = ; i < heap_size; i++)
printf("%d ", data[i]);
printf(", ");
if (heap_size < (int)data.size()) {
printf("Out of heap: ");
for (int i = heap_size; i < (int)data.size(); i++)
printf("%d ", data[i]);
}
printf("\n");
} void heap_test(void) {
int num[] = {, , , , , , , , , };
vector<int> nums(num, num + sizeof(num) / sizeof(int));
// Construct a heap and print it
Heap<int> heap(nums);
heap.print();
// Test maximum() and extract_max()
printf("%d\n", heap.maximum());
printf("%d\n", heap.extract_max());
heap.print();
// Test increase_key()
heap.increase_key(, );
heap.print();
// Test insert_key()
heap.insert_key();
heap.print();
// Test heap_sort()
heap.heap_sort();
heap.print();
} int main(void) {
heap_test();
system("pause");
return ;
}
If you run this code, the expected output is like (I am testing it in Microsoft Visual Studio Professional 2012):
In heap: , In heap: , Out of heap:
In heap: , Out of heap:
In heap: , Out of heap:
In heap: , Out of heap:
Welcome for any question, comment and suggestion about the code!
[Algorithms] Heap and Heapsort的更多相关文章
- Heap Sorting 总结 (C++)
各位读者,大家好. 因为算法和数据结构相关的知识都是在国外学的,所以有些词汇翻译的可能不准确,然后一些源代码的注释可能是英文的,如有给大家带来什么不方便,请见谅.今天我想写一下Heap相关的知识,从基 ...
- 排序算法(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 ...
- 算法 Heap sort
// ------------------------------------------------------------------------------------------------- ...
- David MacKay:用信息论解释 '快速排序'、'堆排序' 本质与差异
这篇文章是David MacKay利用信息论,来对快排.堆排的本质差异导致的性能差异进行的比较. 信息论是非常强大的,它并不只是一个用来分析理论最优决策的工具. 从信息论的角度来分析算法效率是一件很有 ...
- [151225] Python3 实现最大堆、堆排序,解决TopK问题
参考资料: 1.算法导论,第6章,堆排序 堆排序学习笔记及堆排序算法的python实现 - 51CTO博客 堆排序 Heap Sort - cnblogs 小根堆实现优先队列:Python实现 -cn ...
- C语言排序
排序算法 快速排序 C语言快速排序qsort(数组,长度,元素大小,cmp函数(*,*))//注意函数cmp的参数为指针 #include <stdio.h> #include <s ...
- Java与算法之(8) - 堆排序
堆是一种特殊的完全二叉树,其特点是所有父节点都比子节点要小,或者所有父节点都比字节点要大.前一种称为最小堆,后一种称为最大堆. 比如下面这两个: 那么这个特性有什么作用?既然题目是堆排序,那么肯定能用 ...
- 洛谷 P1177 【模板】快速排序【13种排序模版】
P1177 [模板]快速排序 题目描述 利用快速排序算法将读入的N个数从小到大排序后输出. 快速排序是信息学竞赛的必备算法之一.对于快速排序不是很了解的同学可以自行上网查询相关资料,掌握后独立完成.( ...
- 排序算法(Java实现)
这几天一直在看严蔚敏老师的那本<数据结构>那本书.之前第一次学懵懵逼逼,当再次看的时候,发觉写的是非常详细,非常的好. 那就把相关的排序算法用我熟悉的Java语言记录下来了.以下排序算法是 ...
随机推荐
- jqplot使用小心得
这两天做一个项目,需要画饼图,所以在网上搜到jqplot这个插件.下面就说说我对他的简单的使用心得. 先说说我想要的效果:1.我需要修改饼图每个部分的背景色 2.我需要修改饼图里面文本的颜色和字体大小 ...
- 将本地web项目发布到ubuntu上并运行 第一个本地的.net core2.0项目
前置条件 ubuntu已安装dotnet 发布版本dotnet与发布机一致 这里用的是vm 所以直接把本地web项目拷贝到vm中运行的ubuntu系统中 web站点需要将 webapplication ...
- .NET面试题(一)
1.请编程遍历页面上所有TextBox控件并给它赋值为string.Empty? foreach (System.Windows.Forms.Control control in this.Contr ...
- SVN安装配置及安全注意事项
两个脚本: svn遍历脚本.zip wooyun上也是已经有非常多的svn泄露网站信息的事件,有的甚至由此导致整个服务器沦陷: WooYun: [盛大180天渗透纪实]第四章.SVN猎手 (某站SVN ...
- [Yii Framework] Share the session with memcache in Yii
When developing distributed applications with Yii, naturally, we will face that we have to share the ...
- 纯CSS3实现一个旋转的3D立方体盒子
简单介绍 上网易前端微专业课程,里面有一个课外作业是实现一个3D旋转立方体.花了点时间做了下.还有点意思.写个简单教程.供大家学习. 先放上终于要实现的效果 注:代码在chrome 43.0.2357 ...
- 调试JDK1.8源码的方法
背景 在学习JDK源码的时候,免不了需要调试JDK的源码. 比如:想理解ConcurrentHashMap的put(K k, V v)方法,JDK自带的rt.jar文件是支持断点调试,但是却看不到变量 ...
- atitit。html css框架Bootstrap Foundation的比较与不同 attilax大总结
atitit.html css框架Bootstrap Foundation的比较与不同 attilax大总结 1. Bootstrap Foundation的比较与不同1 2. Bootstrap ...
- PHP系统学习3 正则
正则 ^shop 标示匹配与shop开头的字符串 shop$用来匹配与shop结尾的字符串 ^shop$只匹配shop [a-z]匹配所有小写字母 [A-Z]匹配所有大写字母 [a-zA-Z]匹配所有 ...
- ext异常,ExceptionReturn
package cn.edu.hbcf.common.vo; import java.io.PrintWriter; import java.io.StringWriter; /** * Ext 异常 ...