2022-04-07_建大堆实现数组升序

这篇博客展示了如何实现HeapSort算法,包括创建三个文件:HeapSort.c、HeapSort.h和HeapSortFunc.c。HeapSort.c包含了主函数,调用排序函数并打印升序后的数组。HeapSort.h包含函数声明,而HeapSortFunc.c则实现了交换、向上调整和向下调整的函数。整个过程详细解释了如何通过建堆和调整实现升序排序。
摘要由CSDN通过智能技术生成

一、创建三个文件

 

 

二、代码实现

1.HeapSort.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include"HeapSort.h"



void HeapSort(int* data, int n)
{
	//向上调整_建堆
	for (int i = 1; i < n; i++)
	{
		HeapAdjustUp(data, i);
	}
	for (int i = 0; i < n; i++)
	{
		printf("%d ", data[i]);
	}
	printf("\n");

	//升序
	size_t end = n - 1;
	while (end > 0)
	{
		Swap(&data[0], &data[end]);
		HeapAdjustDown(data, end, 0);
		--end;
	}
}



int main()
{
	int data[] = {4,2,7,8,5,1,0,6};
	//升序处理
	HeapSort(data, sizeof(data) / sizeof(int));

	//打印升序后的数据
	for (int i = 0; i < sizeof(data) / sizeof(int); i++)
	{
		printf("%d ", data[i]);
	}
	printf("\n");
	return 0;
}

2.HeapSort.h

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>


//1.交换数值函数声明
void Swap(int* pa, int* pb);


//2.向上调整函数声明
void HeapAdjustUp(int* data, size_t child);


//3.向下调整函数声明
void HeapAdjustDown(int* data, size_t size, size_t rootpos);

3.HeapSortFunc.c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include"HeapSort.h"


//1.交换数值函数实现
void Swap(int* pa, int* pb)
{
	int tmp = 0;
	tmp = *pa;
	*pa = *pb;
	*pb = tmp;
}



//2.向上调整函数实现
void HeapAdjustUp(int* data, size_t childpos)
{
	if (childpos == 0)
	{
		return;
	}
	size_t parentpos = (childpos - 1) / 2;

	while (childpos > 0)
	{
		//建大堆
		if (data[childpos] > data[parentpos])
		{
			Swap(&data[childpos], &data[parentpos]);
			childpos = parentpos;
			parentpos = (childpos - 1) / 2;
		}
		else
		{
			break;
		}
	}
}



//3.向下调整函数实现
void HeapAdjustDown(int* data, size_t size, size_t rootpos)
{
	size_t parentpos = rootpos;
	size_t childpos = parentpos * 2 + 1;
	while (childpos < size)
	{
		if (childpos + 1 < size && data[childpos + 1] > data[childpos])
		{
			childpos++;
		}

		if (data[childpos] > data[parentpos])
		{
			Swap(&data[childpos], &data[parentpos]);
			parentpos = childpos;
			childpos = parentpos * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值