堆排序及调整算法

本文详细介绍了堆排序算法中的两个关键函数adjust_up和adjust_down,解释了如何构建和维护大堆和小堆结构,以及堆排序的核心思想和步骤。
摘要由CSDN通过智能技术生成

调整算法

向上调整:

对大堆向上调整:

 adujust_up

void adjust_up(int* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			swap(a[child], a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else//默认是大堆
		{
			break;
		}
	}
}

向下调整:

有一个前提,那就是左右子树都是小堆。

adjust_down

void adjust_down(int* a, int n,int root)
{
	int parent = root;
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1<n&&a[child + 1] > a[child])//在不是满二叉树的情况下,可能出现只有左孩子没有右孩子
		{
			child++;
		}
		if (a[parent] < a[child])
		{
			swap(a[parent], a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else//已经是小堆的情况下,如果左右孩子中小的那个比父亲大,则跳出循环
		{
			break;
		}
	}
}

堆排序

堆排序的核心思想是建堆。

排升序建大堆。

以免树的关系发生混乱。

void heap_sort(int* a, int n)
{
	for (int i = (n - 1 - 1) / 2; i >= 0; --i)
	{
		adjust_down(a, n, i);
	}
	int end = n - 1;
	while (end > 0)
	{
		swap(a[0], a[end]);
		adjust_down(a, end, 0);
		--end;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值