代码:
def heap_sort(array, n, length):
l = 2*n + 1
r = 2*n + 2
if l <= length - 1:
heap_sort(array, l, length)
if r <= length - 1:
heap_sort(array, r, length)
if l >= length:
return
index = l
if r < length and array[r] > array[l]:
index = r
if array[n] < array[index]:
array[n], array[index] = array[index], array[n]
测试:
if __name__ == '__main__':
a = input("输入数组元素:").split(" ")
a = list(map(int, a))
b = a.copy()
c = a.copy()
for i in range(len(c)):
heap_sort(c, 0, len(c) - i)
c[0], c[len(c) - i - 1] = c[len(c) - i - 1], c[0]
print(c)
输入数组元素:4 8 3 6 7 1 5
[1, 3, 4, 5, 6, 7, 8]
Process finished with exit code 0
声明:本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果用户发布的作品侵犯了您的权利,请联系管理员:wupeng@hqwx.com
环球青藤
官方QQ群扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群