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

来源:互联网 发布:ansys软件界面 编辑:程序博客网 时间:2024/05/04 15:26

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


#include <stdio.h>const long MaxSizeOfPile = 999;const long MaxNum = 9999;// The Min Pilestruct 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;}


0 0
原创粉丝点击