动手实现 算法 之 “堆排序”

由于最小堆插入删除之后能够保持每个子节点都大于父节点,因此只要每次删除根节点(最小节点)就能够得到有序序列


#include <stdio.h>

const long MaxSizeOfPile = 999;
const long MaxNum = 9999;

// The Min Pile
struct Pile {
    int arr[MaxSizeOfPile];
    int size;
};

void InitPile(struct Pile * pile) {
    pile->size = 0;
}

void Insert(struct Pile * pile, int data) {
    int pos = pile->size+1;
    pile->arr[pos] = data;
    while(pile->arr[pos] < pile->arr[pos/2] && pos > 1) {
        int temp = pile->arr[pos];
        pile->arr[pos] = pile->arr[pos/2];
        pile->arr[pos/2] = temp;
        pos /= 2;
    }
    ++pile->size;
}

int Min(struct Pile * pile) {
    return pile->arr[1];
}

int EraseMin(struct Pile * pile) {
    int result = pile->arr[1];
    if(pile->size%2 == 0) {
        pile->arr[pile->size+1] = MaxNum;
    }
    int pos = 2, leaf = pos;
    while(pos <= pile->size) {
        if(pile->arr[pos] < pile->arr[pos+1]) {
            pile->arr[pos/2] = pile->arr[pos];
            leaf = pos;
        } else {
            pile->arr[pos/2] = pile->arr[pos+1];
            leaf = ++pos;
        }
        pos *= 2;
    }
    if(pile->size > 0) {
        pile->arr[leaf] = pile->arr[pile->size];
        --pile->size;
    }
    return result;
}

int main(void)
{
    const int N = 7;
    int a[N] = {3, 10, 9, 11, 12, 5, 2};
    struct Pile pile;
    InitPile(&pile);
    for(int i=0; i<N; i++) {
        Insert(&pile, a[i]);
    }
    for(int i=0; pile.size > 0; i++) {
        a[i] = EraseMin(&pile);
    }
    for(int i=0; i<N; i++) {
        printf("%d ", a[i]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值