1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
def maxheap(a, i, size): l = 2 * i + 1 r = 2 * i + 2 large = i if l < size and a[l] > a[large]: large = l if r < size and a[r] > a[large]: large = r if large != i: a[i], a[large] = a[large], a[i] maxheap(a, large, size)
def buildheap(a, size): for i in range(size >> 1, -1, -1): maxheap(a, i, size)
def insert(a, val, size): a.append(val) assert a[size - 1] == val i = size - 1 p = i >> 1 while p >= 0 and a[p] < a[i]: a[p], a[i] = a[i], a[p] i = p p = i >> 1
def main(): nums = [3, 2, 5, 1, 4] heapsize = len(nums)
buildheap(nums, heapsize) print(nums)
heapsize += 1 insert(nums, 6, heapsize) print(nums)
heapsize -= 1 nums[0], nums[heapsize] = nums[heapsize], nums[0] maxheap(nums, 0, heapsize) print(nums)
if __name__ == '__main__': main()
|