堆排序(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;   }


原创粉丝点击