import math
# 需排序个数
n = 9
# 单个排序
def heap_objust(lis: list, i, n):
while 2 * i <= n:
max_child_index = 2 * i
rmax_child_index = max_child_index + 1
if 2 * i < n and lis[rmax_child_index] > lis[max_child_index]:
max_child_index = rmax_child_index
if lis[i] < lis[max_child_index]:
lis[i], lis[max_child_index] = lis[max_child_index], lis[i]
i = max_child_index
else:
break
return lis
# 构造大顶堆
def heap(lis: list, n):
for i in range(n // 2, 0, -1):
heap_objust(lis, i, n)
return lis
x = heap([0, 11, 12, 13, 14, 15, 16, 17, 18, 19], n)
# 进行排序
def sort(lis: list, n):
while n > 1:
lis[n], lis[1] = lis[1], lis[n]
n -= 1
if n == 2 and lis[1] < lis[2]:
break
heap_objust(lis, 1, n)
return lis
print(sort(x, 9))