先上代碼ide
#include <stdio.h> #include <stdlib.h> void printf_array(int a[], int length) { int i = 0; printf("array element:\n"); for (i = 0; i < length; i++) { printf("%d\t",a[i]); } printf("\n"); } void perDown(int a[], int parent, int length) { int temp = a[parent]; int child = 2 * parent + 1; while (child < length) { if(child + 1 < length && a[child+1] > a[child]) {//獲取較大的兒子節點 child++; } if(a[child] > temp) { a[parent] = a[child]; parent = child; child = parent * 2 + 1; } else {//跳出循環 //a[parent] = temp;//爲何放在這裏很差使呢? //懷疑編譯器進行了內部優化致使此問題,放在這裏和放在while體外,原則上是同樣的意思 break; } } a[parent] = temp; printf_array(a, length); } //構建大根堆 void build_big_heap(int a[], int length) { int i = 0 ; for (i = (length - 2) / 2; i >= 0; i--) { perDown(a, i, length); } } void heap_sort_increasing(int a[], int length) { int i = 0; int temp = 0; build_big_heap(a, length); printf("=========================================\n"); //去掉堆頭,從新排序 for (i = length - 1; i > 0; i--) { temp = a[i]; a[i] = a[0]; a[0] = temp; perDown(a, 0, i); } } int main() { int array[] = {4,2,5,1,7,3}; printf_array(array, 6); heap_sort_increasing(array, 6); printf_array(array, 6); return 0 ; }