python中堆排序算法如何实现?
716次观看
标签:
算法
如何实现
python
老师回答
代码:
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
©本文版权归环球青藤所有,任何形式转载请联系我们。
免费直播
精选课程
相关推荐