defPush(k): global tot global heap heap.append(k) tot += 1 i = tot while i > 1: if heap[i // 2] > heap[i]: heap[i // 2], heap[i] = heap[i], heap[i // 2] i //= 2 else: break return
defPop(): global tot global heap heap[tot], heap[1] = heap[1], heap[tot] heap.pop() tot -= 1 i = 1 while i * 2 < tot: minn = i * 2 if heap[minn] > heap[i * 2 + 1]: minn += 1 if heap[minn] < heap[i]: heap[i], heap[minn] = heap[minn], heap[i] i = minn else: break if i * 2 == tot and heap[tot] < heap[i]: heap[tot], heap[i] = heap[i], heap[tot] return
defPush(k): global tot global heap heap.append(k) tot += 1 i = tot while i > 1: if heap[i // 2] > heap[i]: heap[i // 2], heap[i] = heap[i], heap[i // 2] i //= 2 else: break return
defTop(): global heap return heap[1]
defPop(): global tot global heap heap[tot], heap[1] = heap[1], heap[tot] heap.pop() tot -= 1 i = 1 while i * 2 < tot: minn = i * 2 if heap[minn] > heap[i * 2 + 1]: minn += 1 if heap[minn] < heap[i]: heap[i], heap[minn] = heap[minn], heap[i] i = minn else: break if i * 2 == tot and heap[tot] < heap[i]: heap[tot], heap[i] = heap[i], heap[tot] return
defheap_sort(lis): for i in lis: Push(i) noww = len(lis) for i inrange(noww): lis[i] = Top() Pop() return
if __name__ == '__main__': lis = [100000 - i for i inrange(100000)] print("The original array is:") print(lis) heap_sort(lis) print("The heap_sorted array is:") print(lis)