qscool 2019-11-08
#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 ; }