堆排序 c++实现

堆排序算法

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

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值