用最小堆实现最小优先级队列:
//返回堆中关键字最小的元素
HeapMinimum()
//去掉并返回堆中关键字最小的元素
HeapExtractMin()
//将堆中元素x的关键字减小到k,k要小于x原来的关键字值
HeapDecreaseKey()
//将元素x插入到堆中
MInHeapInsert()
#include <stdio.h>
#include <string.h>
#include <time.h>
#define BUFFER_SIZE 10
//堆调整,保持堆的性质
void MinHeapIfy(int *a,int i,int heapSize)
{
int left=0;
int right=0;
int smallest=i;
int tmp=0;
while(i<heapSize)
{
left=i<<1;
right=(i<<1)+1;
smallest=i;
if(left<=heapSize&&a[i]>a[left])
{
smallest=left;
}
if(right<=heapSize&&a[smallest]>a[right])
{
smallest=right;
}
if(smallest!=i)
{
tmp=a[i];
a[i]=a[smallest];
a[smallest]=tmp;
i=smallest;
}
else
{
break;
}
}
}
//建堆
void BuildMinHeap(int *a,int heapSize)
{
int i=0;
for(i=heapSize/2;i>0;i--)
{
MinHeapIfy(a,i,heapSize);
}
}
//返回堆中具有最小关键字的元素
int HeapMinimum(int *a)
{
return a[1];
}
//去掉并返回堆中具有最小关键字的元素
int HeapExtractMin(int *a,int *heapSize)
{
int min=a[1];
a[1]=a[*heapSize];
(*heapSize)--;
MinHeapIfy(a,1,*heapSize);
return min;
}
//将堆中元素x的关键字值减小到k,k要小于x原关键字的值
void HeapDecreaseKey(int *a,int x,int k)
{
int tmp=0;
if(k>=a[x])
{
return;
}
a[x]=k;
while(x>1&&a[x]<a[x>>1])
{
tmp=a[x];
a[x]=a[x>>1];
a[x>>1]=tmp;
x>>=1;
}
}
//把元素x插入堆中
void MinHeapInsert(int *a,int x,int *heapSize)
{
a[*heapSize+1]=x+1;//赋予新添加的值不能小于x,因为还要调用HeapDecreaseKey()将它的值减小到x
HeapDecreaseKey(a,*heapSize+1,x);
(*heapSize)++;
}
//输出堆中的元素
void Output(int *a,int len)
{
int i=0;
for(i=1;i<len+1;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
int main()
{
int i=0;
int heapSize=BUFFER_SIZE;
int a[BUFFER_SIZE+1];
memset(a,0,sizeof(a));
srand((unsigned)time(NULL));
for(i=1;i<BUFFER_SIZE+1;i++)
{
a[i]=rand()%BUFFER_SIZE+1;
}
printf("随机生成的数组:");
Output(a,BUFFER_SIZE);
//建堆
BuildMinHeap(a,heapSize);
printf("新建的堆为:");
Output(a,heapSize);
//返回堆中关键字最小的元素
printf("堆中关键字最小的元素:%d\n",HeapMinimum(a));
//去掉并返回堆中关键字最小的元素
HeapExtractMin(a,&heapSize);
printf("去掉并返回堆中关键字最小的元素:");
Output(a,heapSize);
//将堆中第四个元素的值减小到-1
HeapDecreaseKey(a,4,-1);
printf("将堆中第四个元素的值减小到-1后,堆为:");
Output(a,heapSize);
//将-5插入到堆中
MinHeapInsert(a,-5,&heapSize);
printf("将-5插入到堆中后,堆为:");
Output(a,heapSize);
system("pause");
return 0;
}