堆排序的python實現
阿新 • • 發佈:2018-12-01
終於完成了堆排序的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)