堆排序

堆排序需要两个主要函数  1.HeapAdust 主要功能是沿着key较大的孩子节点向下筛选。刚建大顶堆的时候需要从length/2的子父亲开始,逐渐建立大顶堆。然后让最大的跟最后的元素交换。此时要从新对unordered 的堆进行调整。主要程序如下:

头函数:c9-7

#define MAX_SIZE 20
typedef int KeyType;
struct RedType
{
	KeyType key;
	InfoType otherinfo;
};

struct SqList
{
	RedType r[MAX_SIZE];
	int length;
};


c10-1

#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)<=(b))

程序:

#include<stdio.h>
typedef int InfoType;
#include"c9-7.h"
#include"c10-1.h"
typedef SqList HeapType;
void HeapAdjust(HeapType &H,int s,int m)
{
	RedType rc;
	int j;
	rc=H.r[s];
	for(j=2*s;j<=m;j*=2)
	{
		if(j<m&<(H.r[j].key,H.r[j+1].key))
			++j;
		if(!LT(rc.key,H.r[j].key))
			break;
		H.r[s]=H.r[j];
		s=j;
	}
	H.r[s]=rc;
}

void HeapSort(HeapType &H)
{
	RedType t;
	int i;
	for(i=H.length/2;i>0;--i)
	HeapAdjust(H,i,H.length);
	for(i=H.length;i>1;--i)
	{
		t=H.r[1];
		H.r[1]=H.r[i];
		H.r[i]=t;
		HeapAdjust(H,1,i-1);
	}

}

void print(HeapType H)
{
	int i;
	for(i=1;i<=H.length;i++)
	printf("(%d,%d)",H.r[i].key,H.r[i].otherinfo);
	printf("\n");
}

#define N 8
void main()
{
	RedType d[N]={{49,1},{38,2},{65,3},{97,4},{76,5},{13,6},{27,7},{49,8}};
	HeapType h;
	int i;
	for(i=0;i<N;i++)
	 h.r[i+1]=d[i];
	h.length=N;
	printf("排序前:\n");
	print(h);
	HeapSort(h);
	printf("排序后:\n");
	print(h);
}

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值