堆排序和 优先队列

#include"head.h"

static int left(int i)
{
	return (i<<1);
}

static int right(int i)
{
	return ((i<<1)+1);
}

static int parent(int i)
{
	return (i/2);
}

void swap(ElementType *x,ElementType *y)
{
	ElementType tmp;
	tmp=*x;
	*x=*y;
	*y=tmp;
}

void maxHeapIfy(ElementType a[],int i,int n)
{
	int l,r,largest;

	l=left(i);
	r=right(i);

	if(l<=n && a[l]>a[i])
		largest=l;
	else
		largest=i;
	if(r<=n && a[r]>a[largest])
		largest=r;
	if(largest!=i)
	{
		swap(&a[largest],&a[i]);
		maxHeapIfy(a,largest,n);
	}
}


void buildMaxHeap(ElementType a[],int n)
{
	int i;

	for(i=n/2;i>=1;i--)
		maxHeapIfy(a,i,n);
}


void heapSort(ElementType a[],int n)
{
	int i;

	buildMaxHeap(a,n);
	for(i=n;i>1;i--)
	{
		swap(&a[1],&a[i]);
		maxHeapIfy(a,1,i-1);
	}
}
		
ElementType heapMaximum(ElementType a[])
{
	return a[1];
}
ElementType heapExtractMax(ElementType a[],int *heapSize)
{

	ElementType max;

	if(*heapSize<1)
		return 0;
	max=a[1];
	a[1]=a[*heapSize-1];
	--*heapSize;
	maxHeapIfy(a,1,*heapSize);
	return max;
}
	
void heapIncreaseKey(ElementType a[],int i,ElementType key)
{
	if(key<a[i])
		exit(1);
	a[i]=key;
	while(i>1 && a[parent(i)]<a[i])
	{
		swap(&a[i],&a[parent(i)]);
		i=parent(i);
	}
}

void maxHeapInsert(ElementType a[],ElementType key,int *heapSize)
{
	a[*heapSize]=INF;
	heapIncreaseKey(a,*heapSize,key);
}

void heapDelete(ElementType a[],int i,int *heapSize)
{
	ElementType key;
	a[i]=a[*heapSize-1];	
	--(*heapSize);
	key=a[i];
	if(key<=a[parent(i)])
		maxHeapIfy(a,i,*heapSize);
	else
	{
		while(i>1 && a[parent(i)]<a[i])
		{
			swap(&a[i],&a[parent(i)]);
			i=parent(i);
		}
	}
}
	

#define INF -10000
#define MAX 11
#define MAXLENTH 10
typedef int ElementType;

void buildMaxHeap(ElementType a[],int n);
void heapSort(ElementType a[],int n);
void heapDelete(ElementType a[],int i,int *heapSize);
void maxHeapInsert(ElementType a[],ElementType key,int *heapSize);
void heapIncreaseKey(ElementType a[],int i,ElementType key);
ElementType heapExtractMax(ElementType a[],int *heapSize);
ElementType heapMaximum(ElementType a[]);
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"head.h"

int main()
{
	int i,h,*heapSize;
	ElementType a[MAX],max;
	
	h=MAXLENTH;
	heapSize=&h;
	srand((unsigned)time(NULL));
	for(i=1;i<*heapSize;i++)
		a[i]=rand()%10+1;

	buildMaxHeap(a,*heapSize);
	//maxHeapInsert(a,0,heapSize);

	//b=heapMaximum(a);
	//printf("%d\n",b);
	//(heapIncreaseKey(a,8,15));
	max=heapExtractMax(a,heapSize);
	printf("%d\n",max);
	//heapSort(a,MAX);
	for(i=1;i<*heapSize;i++)
	{
		printf("%d\t",a[i]);
		if(i%10==0)
			printf("\n");
	}


	return 0;
}




 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值