《算法导论》-优先队列(Python)

import numpy as np


def parent(i):
    return int((i-1)/2)


def left(i):
    return 2 * i + 1


def right(i):
    return 2 * (i + 1)


def max_heapify(A, i):
    l = left(i)
    r = right(i)

    if l + 1 <= A_heapsize and A[l] > A[i]:
        largest = l

    else:
        largest = i

    if r + 1 <= A_heapsize and A[r] > A[largest]:
        largest = r

    if largest != i:
        temp_2 = A[i]
        A[i] = A[largest]
        A[largest] = temp_2

        max_heapify(A, largest)

def build_max_heap(A):
    for i in reversed(range(int(len(A)/2))):
        max_heapify(A, i)


def heap_maximum(A):
    return A[0]


def heap_extract_max(A):
    global A_heapsize

    if A_heapsize < 1:
        print('Error: heap underflow')
        return True

    max = A[0]
    A[0] = A[A_heapsize-1]
    A_heapsize -= 1

    max_heapify(A, 0)
    return max


def heap_increase_key(A, i, key):
    if key < A[i]:
        print('Error: new key is smaller than current key')
        return True

    A[i] = key

    # exchage 操作
    '''
    while i > 0 and A[parent(i)] < A[i]:
        temp = A[parent(i)]
        A[parent(i)] = A[i]
        A[i] = temp
        i = parent(i)
    '''

    # 插入排序中的内循环思想
    while i > 0 and A[parent(i)] < key:
        A[i] = A[parent(i)]
        i = parent(i)
    A[i] = key


def max_heap_insert(A, key):
    global A_heapsize
    A_heapsize += 1
    A[A_heapsize-1] = float('-inf')
    heap_increase_key(A, A_heapsize-1, key)


if __name__ == '__main__':
    A_size = 16
    A = list(np.random.randint(-100, 100, size=A_size))

    A_heapsize = len(A)

    print('The original list is:', A)

    build_max_heap(A)
    max = heap_extract_max(A)

    print('\nThe maximum number of the list is:', max)
    print('\nThe list after extracting max:', A[:A_heapsize])

    heap_increase_key(A, 8, 15)
    print('\nThe list after increasing number:', A)

    max_heap_insert(A, 1000)
    print('\nThe list after insert 1000:', A)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值