排序方法7---堆排序

#include<stdio.h>
#include<iostream>
#define MAXL 100
typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType data;
}RecType;
void swap(RecType &x, RecType &y)
{
	RecType temp;
	temp = x;
	x = y;
	y = temp;
}
void CreateList(RecType R[], KeyType keys[], int n)
{
	for (int i =1 ; i <= n; i++)
	{
		R[i].key = keys[i-1];
	}
}
void Display(RecType R[], int n)
{
	for (int i = 1; i <= n; i++)
	{
		printf("%d", R[i].key);
	}
	printf("\n");
}
void DispHeap(RecType R[], int i, int n)
{
	if (i <= n)
		printf("%d", R[i].key);
	if (2 * i <= n || 2 * i + 1 < n)
	{
		printf("(");
		if (2 * i <= n)
			DispHeap(R, 2 * i, n);
		printf(",");
		if (2 * i + 1 <= n)
			DispHeap(R, 2 * i + 1, n);
		printf(")");
	}
}
void sift(RecType R[], int low, int high)
{
	int i = low, j = 2 * i;     					//R[j]是R[i]的左孩子
	RecType temp = R[i];
	while (j <= high)
	{
		if (j<high && R[j].key<R[j + 1].key) 	//若右孩子较大,把j指向右孩子
			j++;    						//变为2i+1
		if (temp.key<R[j].key)
		{
			R[i] = R[j];              		//将R[j]调整到双亲结点位置上
			i = j;                    		//修改i和j值,以便继续向下筛选
			j = 2 * i;
		}
		else break;                 		//筛选结束
	}
	R[i] = temp;                      		//被筛选结点的值放入最终位置
}

void HeapSort(RecType R[], int n)
{
	int i,j,count=1;
	for (i = n / 2; i >= 1; i--)	//循环建立初始堆,调用sift算法 n/2 次
		sift(R, i, n);
	printf("初始堆:"); DispHeap(R, 1, n); printf("\n");
	for (i = n; i >= 2; i--)		//进行n-1趟完成推排序,每一趟堆排序的元素个数减1
	{
		printf("第%d趟排序:", count++);
		printf("交换%d与%d,输出%d     ", R[i].key, R[1].key, R[1].key);
		swap(R[i], R[1]);
		printf("排序结果:");
		for (j = 1; j <= n; j++)
			printf("%2d", R[j].key);
		printf("\n");
		printf("\n");
		sift(R, 1, i - 1);//对R[1..i-1]进行筛选,得到i-1个节点的堆
		printf("筛选调整得到堆:");
		DispHeap(R, 1, i - 1);
		printf("\n");
	}
}
int main()
{
	int n = 10;
	RecType R[MAXL];
	KeyType a[] = { 6,8,7,9,0,1,3,2,4,5 };
	CreateList(R, a, n);
	printf("排序前:"); Display(R, n);
	HeapSort(R, n);
	printf("\n");
	printf("排序后:"); Display(R, n);
	system("pause");
	return 1;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值