堆排序(大顶堆->升序)

#include <stdlib.h>
#include <stdio.h>

/* 堆排序 */
void HeapAdjust(int a[],int index,int n)
{   //注意规定a[0]不存放元素,当做缓存用
    int i,father = index,son;

    a[0] = a[index];
    for(son=2*father; son<=n; son*=2)//比较子节点
    {
        if(son<n && a[son+1] > a[son])son++;//右节点更大
        if(a[son] < a[0] )break;//不需要继续了

        a[father] = a[son];//大的上提
        father = son;
    }
    a[father] = a[0];
}
void HeapSort(int a[],int n)
{   //注意规定a[0]不存放元素,当做缓存用
    int i;
    for(i=n/2; i>0; i--)//从最后一个非叶节点开始从下往上建立大顶堆
        HeapAdjust(a,i,n);
    for(i=n; i>1; i--)//不断抽取堆顶,调整
    {
        a[0] = a[i];
        a[i] = a[1];
        a[1] = a[0];
        HeapAdjust(a,1,i-1);
    }
}
int main(int argc, char *argv[])
{
    int a[] = {-1,4,5,3,2,9,8,1,7,6,0};
    int i;

    HeapSort(a,10);
    for(i=1; i<=10; i++)printf("%d\t",a[i]);
    printf("\n");
    return 1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值