堆
来源:互联网 发布:贵州师大教务网络系统 编辑:程序博客网 时间:2024/05/22 05:05
堆是一种数组对象,维基百科。
堆实现代码:
#include<iostream>#include<vector>#include<algorithm>using namespace std;int heap_size;inline int LEFT(int i){return 2 * i + 1;}inline int RIGHT(int i){return 2 * (i + 1);}void display(int a[], int n){for (int i = 0; i < n; i++)cout << a[i] << " ";cout << endl;}void swap(int& n, int& m){int temp;temp = n;n = m;m = temp;}void max_heapify(int a[], int i){int l = LEFT(i);int r = RIGHT(i);int largest;if ((l < heap_size) && a[l] > a[i])largest = l;elselargest = i;if ((r < heap_size) && a[r] > a[largest])largest = r;/*if (largest != i){swap(a[largest], a[i]);max_heapify(a, largest);}*/while (largest!=i){swap(a[largest], a[i]);i = largest;l = LEFT(i);r = RIGHT(i);if (l<heap_size&&a[l]>a[i]){largest = l;}else{largest = i;}if (r<heap_size&&a[r]>a[i]){largest = r;}}}
int main(){<span style="white-space:pre"></span>int a[100];<span style="white-space:pre"></span>int n;<span style="white-space:pre"></span>while (cin >> n)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>for (int i = 0; i < n; i++)<span style="white-space:pre"></span>cin >> a[i];<span style="white-space:pre"></span>heap_sort(a, n);<span style="white-space:pre"></span>display(a, n);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return 0;}(2)在C++的STL中,有对堆的操作:点击打开链接。
代码如下:
int main(){int a[] = { 1,4,5,6,7,8,3,2 };vector<int> ivec(a, a + 5);for (vector<int>::iterator iter = ivec.begin();iter != ivec.end();iter++){cout <<*iter<<" " ;}cout << endl;make_heap(ivec.begin(), ivec.end());cout << "heap is :" << endl;for (vector<int>::iterator iter = ivec.begin();iter != ivec.end();iter++){cout << *iter << " ";}cout << endl;pop_heap(ivec.begin(), ivec.end());ivec.pop_back();cout << "after pop_back:" << endl;for (vector<int>::iterator iter = ivec.begin();iter != ivec.end();iter++){cout << *iter << " ";//cout << endl;}cout << endl;ivec.push_back(99);push_heap(ivec.begin(), ivec.end());cout << "after push_back:" << endl;for (vector<int>::iterator iter = ivec.begin();iter != ivec.end();iter++){cout << *iter << " ";//cout << endl;}cout << endl;sort_heap(ivec.begin(), ivec.end());cout << "after sorting:" << endl;for (vector<int>::iterator iter = ivec.begin();iter != ivec.end();iter++){cout << *iter << " ";//cout << endl;}cout << endl;return 0;}
0 0
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 堆
- 容器技术
- 深入了解RunLoop
- Iptables之FORWARD转发链
- 【Red5】如何搭建环境以及调试Red5(1.0.6版本)应用(一)
- myeclipse
- 堆
- fragment中listview的onitemclicklistener
- iOS中各种风格时间轴的设计及总结
- 倒排索引/布尔检索
- Cloud Insight支持阿里云一键接入了,so what?
- 数据结构与算法系列----学习数据结构与算法前你需要知道的
- 多种Spring.jar详解
- 安卓使用SQLite数据库(创建、增删改查)
- iOS swift 使用基本语法