堆排序中构造最大堆C/C++
来源:互联网 发布:怎么给淘宝客服评价 编辑:程序博客网 时间:2024/04/30 10:12
在堆排序算法中,我们使用的是最大堆。下面的代码是给定一组数,构造一个最大堆。left(heap, location)和right(heap, location)分别返回数组heap中location的左右孩子的索引。max_heapify(heap, i)是确保heap数组的i的左右孩子都满足最大堆化。bulid_max_heap(heap)将heap数组构造一个最大堆。
/*构造一个NUM个数最大堆;*/#include<iostream>#include<ctime>using namespace std;const int NUM = 10;void print(int p[] , int n){for (int i = 1; i <= n; i++){cout << "heap[" << i << "] = " << p[i] << endl;}}int left(int heap[] , int i){return 2 * i;}int right(int heap[] , int i){return 2 * i + 1;}void max_heapify(int heap[], int location){int largest = 0, l, r, temp;l = left(heap, location);r = right(heap, location);if (l <= NUM && heap[l] > heap[location]){largest = l;}elselargest = location;if (r <= NUM && heap[r] > heap[largest]){largest = r;}if (location != largest){temp = heap[location];heap[location] = heap[largest];heap[largest] = temp;max_heapify(heap, largest);}}void bulid_max_heap(int heap[]){//叶子节点不用max_heapify,所以是节点数的一半for (int i = NUM / 2; i >= 1; i--){max_heapify(heap, i);}}int main(){int heap[NUM + 1] = {0};srand(time(NULL));for (int i = 1; i <= NUM; i++){heap[i] = rand() % 100;}print(heap, NUM);bulid_max_heap(heap);cout << "-------------" << endl;print(heap, NUM);return 0;}
结果如下:
0 0
- 堆排序中构造最大堆C/C++
- c 最大堆排序
- C语言 最大堆排序
- 最大堆(c++)实现
- 堆排序----C语言
- 堆排序(C#)
- 堆排序C语言
- HeapSort(堆排序 C++)
- c语言堆排序
- 堆排序(C语言版)
- 堆排序(C++)
- 【c++】堆排序算法
- 堆排序(C#)
- 堆排序(C#)
- 堆排序 ----- C语言
- C算法--堆排序
- 堆排序 C语言版
- C语言堆排序
- 用Apache Spark进行大数据处理
- 位运算将01字符串转化为相应二进制数
- Qt的自文档化工具qdoc
- ExpandableListView替换右边箭头的实现
- llwer
- 堆排序中构造最大堆C/C++
- Swift基本语法思维导图
- 查询mysql数据库有哪些表
- 附录A,cmnhdr.h遇见的问题(目录是原创,答案是转载,搜集自互联网)
- java实现八皇后的排列问题
- c++ 多态
- 坑爹的maven插件-assembly
- 4*4魔方
- Hive安装