堆排序(heap Sort)
来源:互联网 发布:homer软件 编辑:程序博客网 时间:2024/05/21 19:32
Algorithm steps:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.3. Repeat above steps while size of heap is greater than 1.
#include <bits/stdc++.h> using namespace std;const int MAXN = 1024;int arr[MAXN];void heapify(int arr[], int n, int i) { int maxIdx = i; int l = i * 2 + 1; int r = i * 2 + 2; if(l < n && arr[l] > arr[maxIdx]) { maxIdx = l; } if(r < n && arr[r] > arr[maxIdx]) { maxIdx = r; } if(maxIdx != i) { swap(arr[i], arr[maxIdx]); heapify(arr, n, maxIdx); }}void buildHeap(int arr[], int n) { for(int i = n/2 - 1; i >= 0; --i) { heapify(arr, n, i); }}void heapSort(int arr[], int n) { buildHeap(arr, n); for(int i = n-1; i >= 0; --i) { swap(arr[0], arr[i]); heapify(arr, i, 0); }}int main(){ ios::sync_with_stdio(false); int T; cin >> T; while(T--) { int n; cin >> n; for(int i = 0; i < n; ++i) { cin >> arr[i]; } heapSort(arr, n); for(int i = 0; i < n; ++i) { cout << arr[i] << " "; } cout << endl; } return 0; }
阅读全文
0 0
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(Heap-Sort)
- 堆排序(heap sort)
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(heap Sort)
- 堆排序(Heap Sort)
- 堆排序(heap sort)
- 堆排序(Heap Sort)
- 堆排序(Heap-Sort)
- Heap Sort(堆排序)
- 堆排序(Heap Sort)
- 堆排序(Heap Sort)
- 堆排序(Heap Sort)
- 堆排序 (Heap Sort)
- 堆排序(Heap Sort)
- heap sort 堆排序
- 百度车联网API
- red5+java打造直播平台系列 初级
- Python FTP文件传输实现
- 开源项目地址-cloudera版本大数据框架
- 排序总结
- 堆排序(heap Sort)
- oracle怎么让表的一个属性有缺省值
- Mybatis整合Spring
- 常用随机变量及其概率分布
- git本地仓库的概念
- iOS 处理中文网址路径转换
- 浏览器怎么加载页面的?
- android 7.0 添加多用户时跳过wifi报错
- 深入理解mybatis原理(九) Mybatis数据源与连接池