堆排序实例

通用函数:

/* common.h */

#ifndef _COMMON_H
#define _COMMON_H

void swap(int *ap, int *bp);
void print_array(const int array[], int n);

#endif
/* common.c */

#include "common.h"
#include <stdio.h>

void 
swap(int *ap, int *bp)
{
    int tmp;
    
    tmp = *ap;
    *ap = *bp;
    *bp = tmp;
}

void 
print_array(const int array[], int n)
{
    int i;

    for(i = 0; i < n; i++)
        printf("%d ", array[i]);
    printf("\n");
}

堆排序函数:

/* max_heap_sort.h */

#ifndef _MAX_HEAP_SORT_H
#define _MAX_HEAP_SORT_H

void perc_down(int array[], int i, int n);
void heap_sort(int array[], int n);

#endif
/* max_heap_sort.c */

#include "max_heap_sort.h"
#include "common.h"

#define left_child(i)    (2 * (i) + 1)

void 
perc_down(int array[], int i, int n)
{
    int child;
    int tmp;
    
    for(tmp = array[i]; left_child(i) < n; i = child)
    {
        child = left_child(i);
        if(child != n-1 && array[child + 1] > array[child])
            child++;
        if(tmp < array[child])
            array[i] = array[child];
        else
            break;
    }        
    array[i] = tmp;
}

void 
heap_sort(int array[], int n)
{
    int i;
    for(i = n / 2; i >= 0; i--)    /* 建立堆 */
        perc_down(array, i, n);
    for(i = n-1; i > 0; i--)
    {
        swap(&array[0], &array[i]);    /* 删除最大元素,其实是将当前最大堆的最大元素放到堆的末尾 */
        perc_down(array, 0, i);
    }
}

测试函数:

/* max_heap_sort_test.c */

#include "max_heap_sort.h"
#include <stdio.h>

int 
main(void)
{
    int array[] = {31, 24, 45, 67, 54, 87, 98, 12, 15, 89};
    heap_sort(array, 10);
    print_array(array);
}
Makefile:
/* Makefile */

target := test
objs := max_heap_sort_test.o max_heap_sort.o common.o
$(target):$(objs)
    gcc -o $@ $^
%.o:%.c
    gcc -c -o $@ $<

clean:
    rm *.o test

测试结果:

image

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值