实现说明
堆排序建堆取顶(Python)以函数 heapsort、sift_down为骨架。
while root * 2 + 1 <= end 承担全部的逐项处理。
使用要点
- 值得导入的表面是
heapsort;周围的辅助代码对片段是私有的。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 heapsort、sift_down。
签名一览:def heapsort(arr)
代码示例
def heapsort(arr):
n = len(arr)
def sift_down(start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child += 1
if arr[root] < arr[child]:
arr[root], arr[child] = arr[child], arr[root]
root = child
else:
return
for i in range((n - 2) // 2, -1, -1):
sift_down(i, n - 1)
for end in range(n - 1, 0, -1):
arr[0], arr[end] = arr[end], arr[0]
sift_down(0, end - 1)
return arr