#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define swap(a, b) ({
__typeof(a) c = a;
a = b, b = c;
})
int down_updata (int *p, int i, int n) {
int temp = i;
while ((i << 1) <= n) {
p[i] < p[(i << 1)] && (temp = i << 1);
(i << 1 | 1) <= n && p[(i << 1 | 1)] > p[temp] && (temp = (i << 1 | 1));
if (temp == i) break;
swap(p[i], p[temp]);
i = temp;
}
return 0;
}
void output(int *p, int n) {
for (int i = 0; i < n; i++) printf("%d, ", p[i]);
printf("
");
return ;
}
int heap_sort(int *p, int n) {
p -= 1;
for (int i = n >> 1; i > 0; i--) down_updata(p, i, n);
for (int i = n; i > 1; i--) {
swap(p[i], p[1]);
down_updata(p, 1, i - 1);
}
return 1;
}
int main() {
srand(time(0));
#define MAX_N 20
int temp = 1, *ar = (int *)malloc(sizeof(int) * (MAX_N + 1));
for (int i = 0; i < MAX_N; i++) ar[i] = rand() % 100;
output(ar, MAX_N);
heap_sort(ar, MAX_N);
output(ar, MAX_N);
#undef MAX_N
return 0;
}