#include<stdio.h>
void FindMaxInHeap(int arr[], const int size) {
for (int j = size - 1; j > 0; --j) {
int parent = j / 2;
int child = j;
if (j < size - 1 && arr[j] < arr[j+1]) {
++child;
}
if (arr[child] > arr[parent]) {
int tmp = arr[child];
arr[child] = arr[parent];
arr[parent] = tmp;
}
}
}
void HeapSort(int arr[], const int size) {
for (int j = size; j > 0; --j) {
FindMaxInHeap(arr, j);
int tmp = arr[0];
arr[0] = arr[j - 1];
arr[j - 1] = tmp;
}
}
int main()
{
int arr[] = {2, 5, 3, 12, 6, 21, 8, 1};
int n = sizeof(arr) / sizeof(arr[0]);
HeapSort(arr, n);
for (int j = 0; j < n; ++j) {
printf("%3d",arr[j]);
}
printf("\n");
return 0;
}
http://www.tyut.edu.cn/kecheng1/site01/suanfayanshi/heap_sort.asp 堆排序算法动画展示
堆排序--C语言实现,布布扣,bubuko.com
堆排序--C语言实现