算法导论(build the heap iteratively 迭代建堆)
来源:互联网 发布:知网有哪些数据库 编辑:程序博客网 时间:2024/05/17 13:43
#include<iostream>#include<vector>#include<string>#include<set>#include<map>#include<unordered_set>#include<unordered_map>#include<algorithm>#include<xfunctional>using namespace std;typedef struct heap{int arr_size;int heap_size;int *arr;}heap;void Tune(heap& h,int start){int i = start;while (2 * i < h.heap_size){int index = i;int max_temp = h.arr[index];if (h.arr[2 * i]>max_temp){index = 2 * i;max_temp = h.arr[index];}if (2 * i + 1 <= h.heap_size){if (h.arr[2 * i + 1] > max_temp){index = 2 * i + 1;max_temp = h.arr[index];}}if (index == i) return;else{swap(h.arr[index],h.arr[i]);i = index;}}}void BuildHeap(heap &h){for (int i = h.heap_size / 2; i >0; i--){Tune(h,i);}}void heap_sort(heap &h){for (int i = h.heap_size; i > 1; i--){swap(h.arr[1], h.arr[h.heap_size]);h.heap_size--;Tune(h,1);}}int main(){heap h;cout << "Input the size of the array:";cin >> h.arr_size;h.arr = new int[h.arr_size+1];h.heap_size = h.arr_size;cout << "Input the element:";for (int i = 1; i <= h.arr_size; i++) cin >> h.arr[i];BuildHeap(h);cout << "After build:";for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i] << " ";cout << endl;heap_sort(h);cout << "After sort:";for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i]<<" ";cout << endl;system("pause");return 0;}
0 0
- 算法导论(build the heap iteratively 迭代建堆)
- 算法导论(build the heap recursively 递归建堆)
- 算法导论 Exercise2.3-5(implement binary search iteratively)
- 算法导论(Exercise 6.5-9 implement the k-way merge by using heap)
- 算法导论(implement the 4.1 alogrithm)
- 算法导论(Problems 6-2) d-ary heap(多叉树实现堆)
- 算法导论——堆排序(Heap-Sort)
- 算法导论(一)
- 算法导论(一)
- 算法导论(二)
- 红黑树(算法导论)
- 线性规划(算法导论)
- 算法导论(0)
- 算法导论(1)
- 算法导论(2)
- 算法导论(1)
- 算法导论(2)
- 算法导论(三)
- 热标
- Json解析工具Jackson(使用注解)
- Apache maven shade plugin使用说明
- 【连载】研究EasyUI系统—Tree组件(高级属性和用法)
- 动画--飘雪效果
- 算法导论(build the heap iteratively 迭代建堆)
- Spring — IoC详解
- 【DayDayUp】【算法_图_最短路_之二_SPFA最劣、Dij堆优化&Johnson(结点对最短路)】(待续)
- Python基础学习笔记之一
- HTML初识
- httpInvoker提供远程服务调用总结(一)
- Ubuntu14.04下安装mongodb 3.X
- 一些网络方面的试题
- android 字符串 转换成Bitmap 设置文本的字体: 宋体,隶书啥的,获取字体的 行高, 文字生成图片