#include <stdio.h>
#include <assert.h>
void exchange(int* x, int* y)
{
assert(x && y);
int tmp = *x;
*x = *y;
*y = tmp;
}
void Adjustdown(int* a, int sz, int parent)
{
assert(a);
int Child = parent * 2 + 1;
while (Child < sz)
{
if (Child + 1 < sz && a[Child] < a[Child + 1])
{
Child = Child + 1;
}
if (a[Child] > a[parent])
{
exchange(&a[Child], &a[parent]);
parent = Child;
Child = parent * 2 + 1;
}
else
{
break;
}
}
}
void heap_sort(int* a, int sz)
{
assert(a);
// 排升序,建大堆,排降序,建小队
for (int n = (sz - 2) / 2; n >= 0; n--)
{
Adjustdown(a, sz, n);
}
for (int n = sz - 1; n > 0; n--)
{
exchange(&a[0], &a[n]);
Adjustdown(a, n, 0);
}
}
int main()
{
int arr[] = { 1,433,745,39,68,430,573,36 };
int sz = sizeof(arr) / sizeof(arr[0]);
heap_sort(arr, sz);
for (int i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
对数组进行堆排列
最新推荐文章于 2024-10-31 19:07:52 发布