/*
最小优先级队列的实现,为了算法描述方便,数组下标从1开始,下标为0的元素舍弃不用
author:wuzuquan
last_modify:2008-1-11
*/
#include <stdio.h>
#include <limits.h>
#define PARENT(i) ((i)>>1)
#define LEFT(i) ((i)<<1)
#define RIGHT(i) ((LEFT(i))+1)
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int heap_size;
int length;
void min_heaplfy(int *a,int i)
{//使以i为根的子树成为最小堆
int left=LEFT(i);
int right=RIGHT(i);
int smallest=0;
if(left<=heap_size && a[left]<a[i])
smallest=left;
else
smallest=i;
if(right<=heap_size && a[right]<a[smallest])
smallest=right;//select a smallest element
if(smallest!=i)
{
swap(&a[i],&a[smallest]);
min_heaplfy(a,smallest);
}
}
void build_min_heap(int *a)
{//对每一个非叶子结点都调用一次min_heaplfy
int i=0;
heap_size=length;
for(i=length/2;i>=1;i--)
{
min_heaplfy(a,i);
}
}
void heapsort(int *a)
{//堆的递减排序
int i=0;
build_min_heap(a);
for(i=length;i>=2;i--)
{
swap(&a[1],&a[i]);
heap_size=heap_size-1;
min_heaplfy(a,1);
}
}
int minimum(int *a)
{//return the min element
return a[1];
}
int heap_extract_min(int *a)
{//去掉并返回A中具有最小关键字的元素
int min=0;
if(heap_size<1)
printf("heap underflow!/n");
min=a[1];
a[1]= a[heap_size];
heap_size-=1;
min_heaplfy(a,1);
return min;
}
void heap_decrease_key(int *a,int i,int key)
{//将元素I的key的值减少到key
if(key>a[i])
printf("new key is bigger than current key");
a[i]=key;
while( i>1 && a[PARENT(i)]> a[i] )
{
swap(&a[i], &a[PARENT(i)]);
i=PARENT(i);
}
}
void min_heap_insert(int *a, int key)
{
heap_size=heap_size+1;
a[heap_size]=INT_MAX;
heap_decrease_key(a,heap_size,key);
}