#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define LeftChild(i) (2 * (i) + 1)
typedef int ElementType;
void swap(ElementType* a, ElementType* b)
{
ElementType tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
//建立最大堆
void PercDown(ElementType a[], int i, int n)
{
int child;
ElementType tmp;
for(tmp = a[i]; LeftChild(i) < n; i = child)
{
child = LeftChild(i);
if(child != n - 1 && a[child + 1] > a[child])
child++;
if(tmp < a[child])
a[i] = a[child];
else
break;
}
a[i] = tmp;
}
void headSort(ElementType a[], int n)
{
int i;
for(i = n / 2; i >= 0; i--)
PercDown(a, i, n);
for(i = n - 1; i > 0; i--)
{
swap(&a[0], &a[i]);
PercDown(a, 0, i);
}
}
int main()
{
ElementType a[10] = {1, 3, 2, 10, 5, 7, 8, 6, 4, 9};
headSort(a, 10);
for(int i = 0; i < 10; i++)
printf("%-4d", a[i]);
printf("\n");
system("pause");
return 0;
}排序之三:堆排序
最新推荐文章于 2025-04-14 17:23:10 发布
本文介绍了一种基于最大堆的数据排序算法,并通过 C 语言进行了具体实现。文章展示了如何通过 PercDown 函数维护堆的性质,进而实现 heapSort 函数完成数组排序。最后通过一个示例程序验证了算法的有效性。

434

被折叠的 条评论
为什么被折叠?



