数据结构-排序-堆排序


数据结构-排序-堆排序



1.算法思想

  • 堆排序的思想: 通过将所有的记录按排序码建立成一个最大堆或者一个最小堆,堆的根节点就是最大或者最小的值,不断取出根节点的值,并将最后一个记录填充到根节点的位置,同时堆大小减一。继续建立堆,一直重复直到堆的长度为1,就实现了排序的目的。适合于数据集合较大的情况。
  • 演示图来自于菜鸟教程
    在这里插入图片描述

2.算法复杂度

  • 执行时间: O(nlogn)
  • 附加空间: 一个存储最大记录的空间
  • 是否是稳定的排序方法: 不稳定

3.算法实现

#include "stdio.h"

#define MAXSIZE 10

typedef int keytype;

typedef struct {
	keytype key;
	int other;
}recordtype;

typedef struct {
	int length;
	recordtype r[MAXSIZE + 1];
}table;



void swap(table * tab, int i, int max)
{
	//交换两个记录的值
	recordtype temp = tab->r[i];
	tab->r[i] = tab->r[max];
	tab->r[max] = temp;
}

void heapify(table * tab, int i, int length)
{
	int left = 2 * i + 1;//左儿子
	int right = 2 * i + 2;//右儿子
	int max = i;//记录最大记录下标的变量

	//如果左儿子排序码大于根节点的值,则更新最大记录的下标
	if (left<length&&tab->r[left].key>tab->r[max].key)
	{
		max = left;
	}

	//如果右儿子大于根节点的值,则更新最大记录的下标
	if (right<length&&tab->r[right].key>tab->r[max].key)
	{
		max = right;
	}

	//如果确实发生下标更新,则开始更新最大的记录,
	if (i != max)
	{
		swap(tab, i, max);//更新最大的记录
		heapify(tab, max, length);//调整记录位置,使得满足堆成立的要求
	}
}

void buildheap(table * tab, int length)
{
	//建立一个堆 
	for (int i = length / 2; i >= 0; i--)
	{
		heapify(tab, i, length);
	}

}

void heapsort(table * tab)
{
	int length = tab->length;

	buildheap(tab, length);//建立一个堆

	//当获得最大记录,取出,将最后一个记录放到根节点,堆大小减一,继续建立堆,并循环这个过程
	for (int i = length - 1; i > 0; i--)
	{
		swap(tab, 0, i);//将最后一个记录放到根节点
		length--; //堆大小减一
		heapify(tab, 0, length);// 继续建立堆
	}

}

void inputData(table * tab) {

	printf("please input the length:\n");
	scanf("%d", &tab->length);

	printf("please input the data:");
	for (int i = 0; i < tab->length; i++)
	{
		scanf("%d", &tab->r[i].key);
	}
}

void show(table * tab) {

	printf("the result data:");

	for (int i = 0; i < tab->length; i++)
	{
		printf("%d ", tab->r[i].key);
	}
}


void main()
{
	table * tab = malloc(sizeof(table));
	inputData(tab);
	heapsort(tab);
	show(tab);
}

运行截图
在这里插入图片描述
欢迎大家关注我的博客:breeziness123
转载说明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坂田民工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值