源码+注释
#include <stdio.h>
#define LENGTH(arr) (sizeof(arr)/sizeof((arr)[0]))
void heapSort(int arr[], int length);
void adjustHeap(int arr[], int i, int length);
int main() {
int arr[] = {1, 80, 2, 57, 13};
printf("排序前 arr = ");
for (int i = 0; i < LENGTH(arr); i++) {
printf("%d ", arr[i]);
}
printf("\n----------------------------\n");
heapSort(arr, LENGTH(arr));
printf("排序后 arr = ");
for (int i = 0; i < LENGTH(arr); i++) {
printf("%d ", arr[i]);
}
printf("\n----------------------------\n");
return 0;
}
void heapSort(int arr[], int length) {
int temp;
for (int i = length / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, length);
}
for (int i = length - 1; i > 0; i--) {
temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, i);
}
}
void adjustHeap(int arr[], int i, int length) {
int temp = arr[i];
for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
if (k + 1 < length && arr[k] < arr[k + 1]) {
k++;
}
if (arr[k] > temp) {
arr[i] = arr[k];
i = k;
} else {
break;
}
}
arr[i] = temp;
}