07_04.堆排序
def heap_sort(elems): """堆排序""" def siftdown(elems, e, begin, end): i, j = begin, begin * 2 + 1 while j < end: if j + 1 < end and elems[j + 1] < elems[j]: # 找elems[j + 1]与elems[j]中较小的 j += 1 if e < elems[j]: # e在三者中最小,已找到了位置 break elems[i] = elems[j] # elems[j]在三者中最小,上移 i, j = j, 2 * j + 1 elems[i] = e end = len(elems) # 建小顶堆 for i in range(end // 2, -1, -1): siftdown(elems, elems[i], i, end) for i in range((end - 1), 0, -1): e = elems[i] elems[i] = elems[0] # 取最小元素放到最后 siftdown(elems, e, 0, i) # 剩下元素再建小顶堆 e = [1, 3, 6, 4, 5] heap_sort(e) print(e) # [6, 5, 4, 3, 1] e.reverse() print(e) # [1, 3, 4, 5, 6]