堆排序

#include <stdio.h>

#define UINT32 unsigned int

#define HEAP_SIZE   (10)

#define PARENT(i) (i >> 1)
#define LEFT(i) (i << 1)
#define RIGHT(i) ((i << 1) + 1)

static void print_heap(UINT32 a_heap[], UINT32 heap_size)
{
    UINT32 i = 0;

    if (NULL == a_heap)
    {
        printf("ERROR: a_heap is NULL\n");
        return;
    }

    if (heap_size <= 0)
    {
        printf("ERROR: heap_size is ERR\n");
        return;
    }

    for (i = 1; i <= heap_size; i++)
    {
        printf("%d ", a_heap[i]);
    }
    printf("\n");

}

static void max_heapify(UINT32 a_heap[], UINT32 heap_size, UINT32 i)
{
    UINT32 left = LEFT(i);
    UINT32 right = RIGHT(i);
    UINT32 largest = 0;
    UINT32 temp = 0;

    if (NULL == a_heap)
    {
        printf("ERROR: a_heap is NULL!\n");
        return;
    }

    if (i <= 0 || i > heap_size)
    {
        return;
    }

    if (left <= heap_size && left > 0)
    {
        if (a_heap[left] > a_heap[i])
        {
            largest = left;
        }else{
            largest = i;
        }
    }

    if (right <= heap_size && right > 0)

    {
        if (a_heap[right] > a_heap[largest])
        {
            largest = right;
        }
    }

    if (largest <= heap_size
            && largest > 0
            && largest != i)
    {
        temp = a_heap[i];
        a_heap[i] = a_heap[largest];
        a_heap[largest] = temp;
        max_heapify(a_heap, heap_size, largest);
    }
}

/* 建堆 */
static void build_max_heap(UINT32 a_heap[], UINT32 heap_size)
{
    UINT32 i = 0;

    for (i = heap_size / 2; i >= 1; i--)
    {
        max_heapify(a_heap, heap_size, i);
    }
}

/* 堆排序 */
static void heap_sort(UINT32 a_heap[], UINT32 heap_size)
{
    UINT32 i = 0;

    UINT32 temp = 0;

    build_max_heap(a_heap, heap_size);

    for (i = heap_size; i >= 2; i--)
    {
        temp = a_heap[i];
        a_heap[i] = a_heap[1];
        a_heap[1] = temp;
        heap_size--;
        max_heapify(a_heap, heap_size, 1);
    }

}

int main(void)
{
    UINT32 a_heap[HEAP_SIZE + 1] = {0, 1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
    UINT32 heap_size = HEAP_SIZE;

    print_heap(a_heap, heap_size);
    heap_sort(a_heap, heap_size);
    print_heap(a_heap, heap_size);

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值