算法导论 思考题 9-1

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define LEN 20

typedef struct heapType
{
	int *a;
	int heapLen;
}heap,*heapPtr;

void swop(int *a,int *b)
{
	int temp=*a;
	*a=*b;
	*b=temp;
}

int partition(int a[],int p,int r)
{
	int i=p-1,x=a[r],j;
	for(j=p;j<r;j++)
	{
		if(a[j]>x)
		{
			i++;
			swop(&a[j],&a[i]);
		}
	}
	swop(&a[r],&a[i+1]);
	return i+1;
}

int at(int a[],int p,int r,int i)
{
	if(p==r)
		return a[p];
	int q=partition(a,p,r);
	int k=q-p+1;
	if(i==k)
		return a[q];
	else if(i<k)
		return at(a,p,q-1,i);
	else
		return at(a,q+1,r,i-k);
}

void heapMaxify(heapPtr hp,int i)
{
	int max=hp->a[i],maxi=i;
	int l=hp->a[2*i],r=hp->a[2*i+1];
	if(2*i<=hp->heapLen && l>max)
	{
		maxi=2*i;
		max=l;
	}
	if(2*i+1<=hp->heapLen && r>max)
	{
		maxi=2*i+1;
		max=r;
	}
	swop(&hp->a[i],&hp->a[maxi]);
	if(maxi != i)
		heapMaxify(hp,maxi);
}

heapPtr buildHeap(int a[],int len)
{
	heapPtr hp=(heapPtr)malloc(sizeof(heap));
	hp->a=a;
	hp->heapLen=len;
	for(int i=len/2;i>=1;i--)
	{
		heapMaxify(hp,i);
	}
	return hp;
}



int extractMax(heapPtr hp)
{
	if(hp->heapLen<1)
		return INT_MIN;
	int r=hp->a[1];
	hp->a[1]=hp->a[hp->heapLen];
	hp->heapLen--;
	heapMaxify(hp,1);
	return r;
}

void heapSort(heapPtr hp)
{

}

void printA(int a[],int p,int r)
{
	for(int i=p;i<=r;i++)
	{
		printf("%d ",a[i]);
	}
	printf("\n");
}

int main()
{
	int a[10]={INT_MIN,98,23,2,11,6,24,76,84,55};
	int k=5;
	int max;
	heapPtr hp=buildHeap(a,9);
	/*at(a,1,9,k);//a.前k个最大的数
	int index=partition(a,1,9);
	printA(a,1,k);
		
	for(int i=1;i<=k;i++)
	{
		max=extractMax(hp);
		printf("%d ",max);
	}//b.建立一个最大优先队列,并调用extract-max过程k次
	printf("\n");*/
	int *b=(int*)malloc((k+1)*sizeof(int));
	b[0]=INT_MIN;
	at(a,1,9,k);
	for(int i=1;i<=k;i++)
	{
		max=extractMax(hp);
		b[i]=max;
	}//c.利用顺序统计量算法找第k大元素,再对前i大的数排序
	printA(b,1,k);
	getchar();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值