1 def heap_sort(ary): 2 n = len(ary) # 8 3 first = int(n / 2 - 1) # 3 4 for start in range(first, -1, -1): # 3~0 revese 5 max_heapify(ary, start, n - 1) # from start 6 for end in range(n - 1, 0, -1): 7 ary[end], ary[0] = ary[0], ary[end] 8 max_heapify(ary, 0, end - 1) 9 return ary 10 11 12 def max_heapify(ary, start, end): 13 root = start 14 while True: 15 child = root * 2 + 1 16 if child > end: 17 break 18 if child + 1 <= end and ary[child] < ary[child + 1]: 19 child += 1 20 if ary[root] < ary[child]: 21 ary[root], ary[child] = ary[child], ary[root] 22 root = child 23 else: 24 break 25 26 27 def main(): 28 ary = [6, 5, 3, 1, 8, 7, 2, 4] 29 heap_sort(ary) 30 31 print(ary) 32 33 main()
//Py自带的两种算法,一个sorted(ary)不影响本身结构,可ary.sort()就影响了
学习
挑战了一把当年讳莫如深的堆排,现在理解其实不难,就是一个使用二叉来减少比较次数的快速排序
各种py排序算法
http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
时间: 2024-11-06 09:34:09