您的位置:首页 > 其它

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

2015-05-09 23:27 148 查看
由于最小堆插入删除之后能够保持每个子节点都大于父节点,因此只要每次删除根节点(最小节点)就能够得到有序序列

#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
= {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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: