堆排序(用的向下调整建堆)

#define  _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
 }


void adjustup(int* a, int child)//Efficiency is not as good as downward adjustment
{
	int partent = (child - 1) / 2;//The index should start from 0
	while (child>0)
	{
		if (a[child] < a[partent])	//小堆
		{
			swap(&a[child], &a[partent]);
			child = partent;
			partent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void adjustDown(int* a, int n, int parent)
{
	int child = (parent * 2) + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] > a[child + 1])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}
void Heapsort(int *a ,int n)
{
	for (int i = (n-1-1)/2; i >=0; i--)//The subscript algorithm is (n-1)/2	{
		adjustDown(a, n, i);
	}

	int end = n - 1;
	while (end > 0)
	{
		swap(&a[0], &a[end]);//end
		adjustDown(a, end , 0);
		end--;
	}
}
int main()
{ 
	int a[8] = { 4,2,8,1,5,6,9,7 };
	Heapsort(a, 8);
	for (size_t i = 0; i < 8; i++)
	{
		printf("%d", a[i]);
	}
	return 0;
}

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值