[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语言记录下来了.以下排序算法是 ...
随机推荐
- Android studio 使用心得(五)—代码混淆和破解apk
这篇文章等是跟大家分享一在Android studio 进行代码混淆配置.之前大家在eclipse上也弄过代码混淆配置,其实一样,大家可以把之前在eclipse上的配置文件直接拿过来用.不管是.cfg ...
- STL 容器(vector 和 list )
1.这个容器的知识点比较杂 迭代器的理解: 1.erase()函数的返回值,它的迭代器在循环遍历中的奇特之处: #define _CRT_SECURE_NO_WARNINGS #include < ...
- Jumpserver web界面跳板机
Jumpserver.org 普通用户 仪表盘 查看主机 上传下载 访问官网 欢迎使用Jumpserver开源跳板机系统 帮助 Log out 查看资产 仪表盘 资产管理 查看资产 主机详细信息列表 ...
- php-fig组织fig-standards的一些标准
参考: http://psr.phphub.org/ https://github.com/php-fig/fig-standards https://github.com/PizzaLiu/PHP- ...
- unity 已知cosA和sinA,求A
和c++中的atan2(y,x)类似,unity中有也Mathf.Atan2(y,x).
- PHP下用Memcache 实现消息队列
Memcache 一般用于缓存服务.但是很多时候,比如一个消息广播系统,需要一个消息队列.直接从数据库取消息,负载往往不行.如果将整个消息队列用一个key缓存到memcache里面, 对于一个很大的消 ...
- Bash中的括号(三)
1.两个小括号用来对整数进行算术运算和逻辑运算,比如. 例如给变量赋值: $ a=+; echo $a + $ (( b = + )); echo $b 1+1 只是一个字符串,而 b 就是一个算术表 ...
- location alias与root
网站的根目录是:/alidata/www/webtest [root@M webtest]# tree /alidata/www/ /alidata/www/ ├── abc.html └── web ...
- JS事件类型详解
一般事件 onclick IE3.N2 鼠标点击时触发 此事件 ondblclick IE4.N4 鼠标双击时触发 此事件 onmousedown IE4.N4 按下鼠标时触发 此事件 onmouse ...
- jdk8 Function
例子 1: // 定义function Function<String, String> fun = parm -> { // 这里是定function中的逻辑 return Str ...