向上/向下调整算法-->Push,pop数据后维持堆结构,并且使数据输出有序的算法

本文详细介绍了堆排序中向上调整算法(用于插入新元素)和向下调整算法(保持堆结构)的原理及C++代码实现,包括`AdjustUp`和`AdjustDown`函数,以及一个使用这些算法进行堆排序的`main`函数示例。
摘要由CSDN通过智能技术生成

1.向上调整算法

核心逻辑:新插入的数据和其的父节点进行比较,根据大小堆的性质来进行比较,然后根据比较情况决定是否交换。

补充知识点,如下图:

代码实现:

void AdjustUp(HPDataType* array, int child)//向上调整算法
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (array[child] < array[parent])//小堆
		{
			Swap(&array[child], &array[parent]);
			child = parent;
			parent = (parent - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

大堆的向上调整只需改变while语句后的符号即可。

2.需要向下调整算法的场景之一就是进行堆排序时,Pop数据后进行维持堆结构时,代码场景如下:

void HPPop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	Swap(&php->array[0], &php->array[php->size - 1]);//交换第一个和最后一个数据。
	php->size--;
	AdjustDown(php->array,php->size,0);//交换后要保持堆结构,进行向下调整。
}

AdjustDown函数实现:

void AdjustDown(HPDataType* arr, int size, int parent)
{
	int child = (parent * 2) + 1;
	while (child < size)
	{
		//使用假设法
		if (child + 1 < size && arr[child + 1] < arr[child])//得到较小值的下标
		{
			++child;
		}
		if (arr[parent] > arr[child])
		{
			Swap(&arr[parent], &arr[child]);
			parent = child;
			child = (parent * 2) - 1;
		}
		else
		{
			break;
		}
	}
}

 向上/向下调整算法是堆排序的核心算法,判断是否成功,可以进行测试

main函数代码:

int main()
{
	HP d1;
	HPInit(&d1);
	int arr[] = { 60,70,65,50,32,100 };
	for (int i = 0; i < sizeof(arr) / sizeof(int); i++)
	{
		HPPush(&d1, arr[i]);
	}
	//printf("%d\n", HPSize(&d1));
	while (!HPEmpty(&d1))
	{
		printf("%d ", HPTop(&d1));
		HPPop(&d1);
	}
	return 0;
}

结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值