终于完成了堆排序的python实现,把代码分享出来,最后的结果是递减排列,如需递增可以删除倒置列表那行
from math import floor
def heap_sort(arr,N):
#big_endian
for begin in range(floor((N-1)/2),-1,-1):
big_endian(arr,begin,N)
for end in range(N-1,0,-1):
arr[0],arr[end] = arr[end],arr[0]
big_endian(arr,0,end)
return arr
def big_endian(arr,start,end):
root = start
while True:
child = root * 2 + 1
if child >= end :
break
if child + 1 < end and arr[child] < arr[child+1] :
child = child +1;
if arr[root] < arr[child]:
arr[root],arr[child] = arr[child],arr[root]
root = child
else:
break
if __name__ == '__main__':
l = [3,1,4,9,6,7,5,8,2,10]
result = heap_sort(l, len(l))
result.reverse()
print(result)