0
点赞
收藏
分享

微信扫一扫

2022-04-07_建小堆实现数组降序

ixiaoyang8 2022-04-13 阅读 15

一、创建三个文件

 

二、代码实现

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 = (n - 1 - 1) / 2; i >= 0; i--)
	{
		HeapAdjustDown(data, n, 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;
		}
	}
}

 

举报

相关推荐

0 条评论