算法导论优先队列实现
因为堆排序不是稳定排序,所以需要在heapfy里额外加个索引,来保证优先队列相同元素先进先出
#include <stdio.h>
#include <stdlib.h>
int m_length=0;
void minheapify(int a[],int i,int length)
{
int left=2*i+1;
int right=2*i+2;
int smallest=0;
int temp=0;
if(left<=length-1 && a[left]<a[i])
{
smallest=left;
}
else
{
smallest=i;
}
if(right <=length-1 && a[right]<a[smallest])
smallest=right;
if(smallest!=i)
{
temp=a[smallest];
a[smallest]=a[i];
a[i]=temp;
minheapify(a,smallest,length);
}
}
void buildminheap(int a[],int length)
{
int i=0;
for(i=length/2-1;i>=0;--i)
{
minheapify(a,i,length);
}
}
int heapextractmin(int a[])
{
if(m_length<1)
{
return 0xFFFFFFFF;
}
int min=a[0];
a[0]=a[m_length-1];
m_length=m_length-1;
minheapify(a,0,m_length);
return min;
}
void heapincreasekey(int a[],int i,int key)
{
int temp=0;
if(key>a[i])
printf("new key is larger than current key\n");
a[i]=key;
while(i>0 && a[i/2]>a[i] )
{
temp=a[i/2];
a[i/2]=a[i];
a[i]=temp;
i=i/2;
}
}
void minheapinsert(int a[],int key)
{
m_length=m_length+1;
a[m_length-1]=0x7FFFFFFF;
heapincreasekey(a,m_length-1,key);
}
int main()
{
int a[100]={0};
int b[]={4,1,3,2,16,9,10,14,8,7};
int i=0;
for(i=0;i<10;++i)
minheapinsert(a,b[i]);
heapextractmin(a);
for(i=0;i<10;++i)
printf("%d ",a[i]);
return 0;
}