[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语言记录下来了.以下排序算法是 ...
随机推荐
- java基础讲解04-----数据类型和运算符
1.java的基本数据类型 1.数值型 { 整数型 byte , short ,int ,long 浮点型 float , double } 2.字符型 3.布尔型 2.运算符 1.赋 ...
- 数据库表syscolumns 各个字段含义 select * from syscolumns where name='textA'
每个数据库创建后都会有一些系统表用来存储该数据库的一些基本信息 每个表和视图中的每列在表中占一行,存储过程中的每个参数在表中也占一行.该表位于每个数据库中. 列名 数据类型 描述 name sysna ...
- NFS介绍
一.NFS服务介绍 NFS是 Network File system的缩写 NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机 ...
- atitit.js的 字符串内容 转义 js处理html
atitit.js的 字符串内容 转义 js处理html 1. js处理html的问题 1 2. js的 字符串内容 转义 1 2.1. 处理流程 1 3. 下面的表格列出了其余的特殊字符,这些特殊 ...
- 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 ...
- iOS开发 -李洪强-清除缓存
// // SetViewController.m // dfhx // // Created by dfhx_iMac_001 on 16/4/5. // Copyright © 2016年 ...
- myeclipce怎么破解
MyEclipse安装文件下载,下载地址 http://www.jb51.net/softs/150886.html 你也可以进入官方网站下载:http://www.myeclipsecn.com/d ...
- 循环节计算---用到find函数
#include <iostream> #include <algorithm> #include <vector> using namespace std; in ...
- 从浏览器输入URL回车发生了什么
在浏览器输入url后回车,整个过程发生了什么?整个过程如果节节细述的话,那非常的复杂.我就简单的描述一下整个过程 1.查询DNS,获取域名对应的IP地址 (1).浏览器搜索自身的DNS缓存 (2).搜 ...
- Quotations中页面弹出的问题