#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void adjustup(int* a, int child)//Efficiency is not as good as downward adjustment
{
int partent = (child - 1) / 2;//The index should start from 0
while (child>0)
{
if (a[child] < a[partent]) //小堆
{
swap(&a[child], &a[partent]);
child = partent;
partent = (child - 1) / 2;
}
else
{
break;
}
}
}
void adjustDown(int* a, int n, int parent)
{
int child = (parent * 2) + 1;
while (child < n)
{
if (child + 1 < n && a[child] > a[child + 1])
{
child++;
}
if (a[child] < a[parent])
{
swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else {
break;
}
}
}
void Heapsort(int *a ,int n)
{
for (int i = (n-1-1)/2; i >=0; i--)//The subscript algorithm is (n-1)/2 {
adjustDown(a, n, i);
}
int end = n - 1;
while (end > 0)
{
swap(&a[0], &a[end]);//end
adjustDown(a, end , 0);
end--;
}
}
int main()
{
int a[8] = { 4,2,8,1,5,6,9,7 };
Heapsort(a, 8);
for (size_t i = 0; i < 8; i++)
{
printf("%d", a[i]);
}
return 0;
}