数据结构-排序-堆排序
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
转载说明出处