第六章堆排序之“最小优先级队列”(练习6.5-3)

用最小堆实现最小优先级队列:

//返回堆中关键字最小的元素

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; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值