排序之三:堆排序

本文介绍了一种基于最大堆的数据排序算法,并通过 C 语言进行了具体实现。文章展示了如何通过 PercDown 函数维护堆的性质,进而实现 heapSort 函数完成数组排序。最后通过一个示例程序验证了算法的有效性。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define LeftChild(i) (2 * (i) + 1)
typedef int ElementType;

void swap(ElementType* a, ElementType* b)
{
	ElementType tmp;
	tmp = *a;
	*a = *b;
	*b = tmp;
}
//建立最大堆
void PercDown(ElementType a[], int i, int n)
{
	int child;
	ElementType tmp;

	for(tmp = a[i]; LeftChild(i) < n; i = child)
	{
		child = LeftChild(i);
		if(child != n - 1 && a[child + 1] > a[child])
			child++;
		if(tmp < a[child])
			a[i] = a[child];
		else
			break;
	}
	a[i] = tmp;
}

void headSort(ElementType a[], int n)
{
	int i;
	for(i = n / 2; i >= 0; i--)
		PercDown(a, i, n);
	for(i = n - 1; i > 0; i--)
	{
		swap(&a[0], &a[i]);
		PercDown(a, 0, i);
	}
}

int main()
{
	ElementType a[10] = {1, 3, 2, 10, 5, 7, 8, 6, 4, 9};
	headSort(a, 10);
	for(int i = 0; i < 10; i++)
		printf("%-4d", a[i]);
	printf("\n");
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值