堆排序 c++实现

来源:互联网 发布:养比特犬体验知乎 编辑:程序博客网 时间:2024/06/10 09:20

堆排序算法

堆排序是先建立一个堆,然后在在堆首的元素放在末尾,例如建立的是大顶堆,则对应的是升序排序。然后再对这个变形了的堆进行再次建立堆,只是把当前的最后一个数据忽略。

#include <iostream>#include <algorithm>using namespace std;int heap[1001];void HeapAdjust(int id, int sz){    int l = 2 * id;    int r = 2 * id + 1;    int m = id;    if(id <= sz/2){        if(l <= sz && heap[l] > heap[m]) m = l;        if(r <= sz && heap[r] > heap[m]) m = r;        if(m != id){            swap(heap[id], heap[m]);            HeapAdjust(m, sz);        }    }}void HeapSort(int n){    for(int i = n/2; i > 0; i--) HeapAdjust(i, n); //build heap    for(int i = n; i > 0; i--){ //把每次大顶放在末尾        swap(heap[1], heap[i]);        HeapAdjust(1, i-1);    }}int main(){    int n;    cin >> n;    for(int i = 1; i <= n; i++) cin >> heap[i];    HeapSort(n);    for(int i = 1; i <= n; i++) cout << heap[i] << " ";    cout << endl;}


原创粉丝点击