堆排序是排序算法的一種,它利用了堆(大根堆或小根堆)的性質(樹中每個結點的值大於其左右孩子的值,根節點爲堆中最大值),將待排序列初始化爲堆,然後將根結點與末尾結點交換值,從樹中刪去末尾結點, 並對根結點進行堆調整使該樹依舊保持堆結構,重複進行以上步驟,直到樹中只剩下根結點
#include <stdio.h>
void swap(int tree[], int i, int j) {
int temp;
temp = tree[i];
tree[i] = tree[j];
tree[j] = temp;
}
//對某個節點進行堆調整
void heapify(int tree[], int n, int i) {
int max, l, r;
l = 2 * i;
r = 2 * i + 1;
max = i;
if(l < n && tree[l] > tree[i]) {
swap(tree, l, i);
max = l;
}
if(r < n && tree[r] > tree[i]) {
swap(tree, r, i);
max = r;
}
//遞歸判斷條件 錯1:不能用while
if(max != i) {
heapify(tree, n, max);
}
}
//對二叉樹初始化爲堆
void heap_build(int tree[], int n) {
int i = (n - 1) / 2;
while(i >= 0) {
heapify(tree, n, i);
i--;
}
}
//堆排序
void heapSort(int tree[], int n) {
heap_build(tree, n);
int i;
for(i = n-1; i > 0; i--) {
swap(tree, 0, i);
heapify(tree, i, 0);//此處循環刪掉最後結點 i,直到根節點
}
}
int main() {
int arr[] = {6,8,10,9,4,5,2,7};
heapSort(arr, 8);
int i = 0;
for(i = 0; i < 8; i++) {
printf("%d\n", arr[i]);
}
}