#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
void printList(int list[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", list[i]);
}
printf("\n");
}
void heapAdjust(int list[], int u, int v) {
int temp = list[u];
int k = u * 2 + 1;
while (k <= v) {
if (k + 1 <= v && list[k] < list[k + 1])
k++;
if (temp >= list[k])
break;
list[u] = list[k];
u = k;
k = u * 2 + 1;
}
list[u] = temp;
}
void heapSort(int list[], int n) {
int i;
for (i = n / 2 - 1; i >= 0; i--)
heapAdjust(list, i, n - 1);
printList(list, n);
for (i = n - 1; i > 0; i--) {
int temp = list[0];
list[0] = list[i];
list[i] = temp;
heapAdjust(list, 0, i - 1);
printList(list, n);
}
}
int main() {
int i, n;
int a[MAX];
while (scanf("%d", &n) == 1) {
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("heapSort:\n");
heapSort(a, n);
}
return 0;
}
标签:temp,int,list,void,printList,heapAdjust,排序
From: https://blog.51cto.com/u_16030624/6459097