C语言堆排序问题排查
先上代码
#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 ; }
相关推荐
lpkwxl 2020-06-17
chensen 2020-11-14
拉斯厄尔高福 2020-11-04
杜倩 2020-10-29
拉斯厄尔高福 2020-10-19
嵌入式资讯精选 2020-10-15
zhaochen00 2020-10-13
penkgao 2020-10-13
yiyilanmei 2020-10-05
wanshiyingg 2020-09-29
Mars的自语 2020-09-27
shenwenjie 2020-09-24
一个逗逗 2020-09-22
flycony 2020-09-13
zhaochen00 2020-08-20
Biao 2020-08-20
qingsongzdq 2020-08-19
penkgao 2020-08-17
cetrolchen 2020-08-14