sort: heapSort

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

/*堆大小*/

int g_heap_size;

void set_heap_size(int heapSize)
{
    g_heap_size = heapSize;
}

int get_heap_size()
{
    return g_heap_size;
}

/*数组中使用树的思想,左右节点*/

#define LCHILD(i) (2 * (i))
#define RCHILD(i) (2 * (i) + 1)

/*堆化*/

void max_heapify(int* A, int i)
{
    int lchild, rchild, largerInd = i;
    int heapSize = get_heap_size();
    
    lchild = LCHILD(i);
    rchild = RCHILD(i);

    if (lchild <= heapSize && A[lchild] > A[i])
    {
        largerInd = lchild;
    }

    if (rchild <= heapSize && A[rchild] > A[largerInd])
    {
        largerInd = rchild;
    }

    if (largerInd != i)
    {
        int tmp = A[i];
        A[i] = A[largerInd];
        A[largerInd] = tmp;
        max_heapify(A, largerInd);
    }
}

/*建堆,大根堆,就是满足父节点大于左右子节点的堆*/

void build_max_heap(int *A, int arrLen)
{
    set_heap_size(arrLen);
    int heapSize = get_heap_size();

    for (int i = heapSize / 2; i >= 1; i--)
    {
        max_heapify(A, i);
    }
}

/*堆排序,把建好的堆,A[1]位置已经是大根堆的最大值,把

它交换到A[heapSize]位置。这里要求A数组是从1下表开始。

截止更新heapSize,重新堆化A[1]*/

void heap_sort(int* A, int arrLen)
{
    build_max_heap(A, arrLen);
    int heapSize = get_heap_size();

    while (heapSize > 1)
    {
        int tmp = A[1];
        A[1] = A[heapSize];
        A[heapSize] = tmp;

        heapSize--;
        set_heap_size(heapSize);

        max_heapify(A, 1);
    }
}

void test_heap_sort()
{
    int A[6] = { 0,5,4,3,2,1 };

    heap_sort(A, 5);

    for (int i = 1; i < 6; i++)
    {
        printf("%d \t",A[i]);
    }
    printf("\n");
}

int main()
{
    test_heap_sort();
    return 0;
}
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值