【经典算法】:对于堆排序的理解及其实现

68 篇文章 1 订阅
60 篇文章 2 订阅

讲讲堆排序的实现步骤:
1,生成堆
2,把堆顶元素放到最后一个
3,调整成为新的堆(这一点至关重要)

堆的二叉结构的实现方式:数组。。。

如果小伙伴还有有堆这种数据结构有不懂的,请参照下方的附录;

最重要的就是调整堆这个函数的书写,其他的都是一些简单的逻辑上面的问题

手撸的C++代码

#include <iostream>
#include <algorithm>
using namespace std;

void HeapAdjust(int *a,int i,int size){
    int lchild = 2*i;
    int rchild = 2*i+1;
    int max = i;
    if(i<=size/2){
        if(lchild<=size && a[lchild]>a[max]){
            max = lchild;
        }
        if(rchild<=size && a[rchild]>a[max]){
            max = lchild;
        }
        if(max!=i){
            swap(a[i],a[max]);
            HeapAdjust(a,max,size);
        }
    }
}
void BuildHeap(int *a,int size){
    int i;
    for(i=size/2;i>=1;i--){
        HeapAdjust(a,i,size);
    }
}
void HeapSort(int *a,int size){
    int i;
    BuildHeap(a,size);
    for(i=size;i>=1;i--){
        swap(a[1],a[i]);
        HeapAdjust(a,1,i-1);//对堆进行调整
    }
}
int main(){
    int a[100];
    int size;
    while(cin>>size &&size>0){
        int i;
        for(i=1;i<=size;i++){
            cin>>a[i];
        }
        HeapSort(a,size);
        for(i=1;i<=size;i++){
            cout<<a[i]<<" ";
        }
    }
}

附录:一个绝对能看懂堆的调整过程的解释
http://blog.csdn.net/zz198808/article/details/7678055

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值