[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语言记录下来了.以下排序算法是 ...
随机推荐
- mysql表属性、索引、约束
1.表属性 创建表的基本语法: create table [if not exists] 表名 (字段列表 [,索引或约束列表])[表选项列表] 其中,字段列表格式如下: 字段名 类型 [属性列表], ...
- CSS经验库
1.兼容360浏览器 字体大小设置 开发中需要使用em单位 font-size: 0.83em; font-family: "Arial"; -webkit-text-size-a ...
- Selenium自動化測試(Python+VS2013)-基礎篇-環境安裝
Python+VS2013環境安裝 http://www.cnblogs.com/aehyok/p/3986168.html PTVS: http://microsoft.github.io/PTVS ...
- Vivado Logic Analyzer的使用
chipscope中,通常有两种方法设置需要捕获的信号.1.添加cdc文件,然后在网表中寻找并添加信号2.添加ICON.ILA和VIO的IP Core 第一种方法,代码的修改量小,适当的保留设计的层级 ...
- ping: icmp open socket: Operation not permitted 的解决办法
ping: icmp open socket: Operation not permitted 的解决办法:为ping加上suid即可.报错时ping的属性: [root@localhost ~]# ...
- 由于没有发现潜在的递归导致MySQL链接数溢出:MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connec
DAOProxy的代码:下面代码中红色高亮的就是出问题的地方,DAOFactory中会构造一个PersonDAOProxy,调用listPersons或者addPerson显然会导致递归,从而导致My ...
- [转载] 关于mkvtoolnix批量处理的
需要的工具:mkvtoolnix.记事本 案例介绍:用文件A的视频+文件B的音频+字幕合成新MKV,在文件列表中,按A.B.C顺序排列.其中A与B都是Mkv格式,所以A与B不能放在同一个文件夹中(就算 ...
- Oracle 错误 maximum number of processes(150) exceeded 解决办法
网上很多同行应该都遇到过这个问题,百度一搜 千篇一律的处理办法,就是加大进程数. 但是我这边情况不一样,因为我的Oracle 11g是早上刚装的,跟本没人用,我用PLSQL链接照样说不能链接. 我就在 ...
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
Could not fetch URL https://pypi.python.org/simple/six/: There was a problem confirming the ssl cert ...
- 【转】Oracle Sys和system用户、sysdba 和sysoper系统权
一:最重要的区别,存储的数据的重要性不同 [sys]所有oracle的数据字典的基表和视图都存放在sys用户中,这些基表和视图对于oracle的运行是至关重要的,由数据库自己维护,任何用户都不能手动更 ...