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的更多相关文章

  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. 解决——CSS :before、:after ,当content使用中文时有时候会出现乱码

    问题: 在进行页面开发时,经常会使用:before, :after伪元素创建一些小tips,但是在:before或:after的content属性使用中文的话,会导致某些浏览器上出现乱码. 例如我遇到 ...

  2. Linux命令-网络命令:ifconfig

    ifconfig 查看本机的网卡信息.eth是linxu真实的网卡,多块网卡从零开始,eth0,eth1. ifconfig eth0 192.168.67.5 设置临时网络IP地址

  3. angularJS 使用自定义指令输出模板

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script sr ...

  4. javascript中call apply的区别

    obj.call(thisObj, arg1, arg2, ...); obj.apply(thisObj, [arg1, arg2, ...]); 两者作用一致,都是把obj(即this)绑定到th ...

  5. 服务器server2008网站iis7+php环境的搭建

    IIS+FastCGI+PHP5_32_Gzip环境搭建-------------------0.装iis71.把php_5.32_win86解压到d:\php2.php.ini文件已经配置好不需要在 ...

  6. DataURL与File,Blob,canvas对象之间的互相转换的Javascript (未完)

    canvas转换为dataURL (从canvas获取dataURL) var dataurl = canvas.toDataURL('image/png'); var dataurl2 = canv ...

  7. 浅谈iOS 5的StoryBoard

    转自:http://blog.163.com/wangy_0223/blog/static/450146612012318113233218/ 示例代码的Github地址:https://github ...

  8. iOS9新特性

    本文主要是说一些iOS9适配中出现的坑,如果只是要单纯的了解iOS9新特性可以看瞄神的开发者所需要知道的 iOS 9 SDK 新特性.9月17日凌晨,苹果给用户推送了iOS9正式版,随着有用户陆续升级 ...

  9. 分时段显示不同的提示的网页JS特效代码

    脚本说明: 把如下代码加入body区域中 <SCRIPT> today=new Date(); var day; var date; var hello; var wel; hour=ne ...

  10. CentOS6.2下安装中文输入法

    因为在程序中需要输入中文,但是系统没有预装中文输入法,所以就安装一下,顺便记录 1.用root登录 ,或su root2.yum install "@Chinese Support" ...