福田汽车与货车帮战略合作:商用车生态转型与物流行业变革
2026/8/18 20:05:25
具体公式如下:
l c h i l d = f a t h e r ∗ 2 + 1 lchild = father * 2 + 1lchild=father∗2+1
r c h i l d = f a t h e r ∗ 2 + 2 rchild = father * 2 + 2rchild=father∗2+2
voidswap(int*a,int*b){inttemp=*a;*a=*b;*b=temp;}voidhepify(int*nums,intsize,inttar){//这里的nums是待排序数组,size是逻辑上的堆排序长度,tar是待调整的子树的根节点下标intlchild=tar*2+1;// 左子节点下标intright=tar*2+2;//右子节点下标intmax=tar;//记录一下左右子节点中有可能的最大值的下标if(lchild<size&&nums[lchild]>nums[max]){max=lchild;//如果该节点拥有子节点并且这个字节点的值比当前的max大时,就更新max为这个值}if(rchild<size&&nums[rchild]>nums[max]){max=rchild;//同理,如果右子节点存在并且值大于当前被更新过的最大值下标的对应值的时候更新最大值为右子节点}if(max!=tar){//这一步是判断左右子结点中是否有比父节点大的值存在,如果有,那么上面的两个if语句会更新max让其不等于tar,进入之后先交换父节点与该节点swap(&nums[max],&nums[tar]);//此时逻辑上的父节点已经被更新为了两个子节点中的较大值,并且父节点也被调整到了子结点上heapify(max);//但是由于被调整下去的父节点也会作为别人的父节点继续干扰大根堆的性质,所以还得对被调整下去的节点进行第二次调整,此时我们就可以递归地调用函数,直到最后的节点符合堆的性质或者说没有子节点为止}}l c h i l d = f a t h e r ∗ 2 + 1 lchild = father * 2 + 1lchild=father∗2+1
r c h i l d = f a t h e r ∗ 2 + 2 rchild = father * 2 + 2rchild=father∗2+2
f a t h e r 和 f a t h e r + 0.5 father 和 father + 0.5father和father+0.5
f a t h e r = ( l c h i l d − 1 ) / 2 = ( r c h i l d − 1 ) / 2 father = (lchild - 1) / 2 = (rchild - 1) / 2father=(lchild−1)/2=(rchild−1)/2
voidheapSort(int*nums,intsize){for(inti=size/2-1;i>=0;i--){//从第一个父节点开始向上挨个调整为堆结构heapify(nums,size,i);}for(inti=n-1;i>=0;i--){//从数组最后一个数的下标开始,将最后一位和0下标处交换,然后缩小数组大小(i—-)swap(&nums[0],&nums[i]);heapify(nums,i,0);//每次交换之后根节点变成最小值,不符合最大堆结构,所以要再对数组第一个数进行排序//由于数组大小在逻辑上一经减一了,所以要传入此时i即为数组大小}}