# 堆排序
# 下调函数
def sift(li, low, high):
# low堆的根结点位置
# high堆的最后一个位置
temp = li[low]
i = low
j = 2*i+1
while j <= high:
if j+1 <= high and li[j] < li[j+1]:
j = j+1
if temp < li[j]:
li[i] = li[j]
i = j
j = 2*i+1
else:
break
li[i] = temp
def heap(li):
n = len(li)
# 建堆
i = (n-2)//2
high = n-1
while i >= 0:
sift(li, i, high)
i -= 1
# 排序
j = n-1
while j >= 0:
li[j], li[0] = li[0], li[j]
sift(li, 0, j-1)
j -= 1
li = [1, 5, 4, 2, 1, 9, 5, 4]
heap(li)
print(li)
02-22
590
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-27
903
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-15
469
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-15
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交