《算法导论》第六章优先队列 python 实现
程序员文章站
2022-05-23 09:57:47
...
优先队列是堆排序的一个应用 :
支持的操作:返回最大值,去掉并返回最大值,插入元素
def max_heapify(A, i, heap_size):
l = 2 * i
r = 2 * i + 1
if l <= heap_size and A[l-1] > A[i-1]:
largest = l
else:
largest = i
if r <= heap_size and A[r-1] > A[largest-1]:
largest = r
if largest == i:
return
else:
A[largest-1], A[i-1] = A[i-1], A[largest-1]
max_heapify(A, largest, heap_size)
def heap_maximum(A): # 返回最大值堆顶元素
return A[0]
def heap_extract_max(A): # 去掉并返回具有最大关键字的元素
n = len(A)
if n < 0:
return "heap underflow"
max = A[0]
A[0] = A[n-1]
n = n-1
max_heapify(A, 0, n)
return max
def heap_increase_key(A, i, key): # 实现插入操作
if key < A[i-1]:
A[i - 1] = key
return "new key is smaller than current key"
A[i-1] = key
while i > 1 and A[int(i/2)-1] < A[i-1]:
A[i-1], A[int(i/2)-1] = A[int(i/2)-1], A[i-1]
i = int(i/2)
def max_heap_insert(A, key):
heap_size = len(A)+1
A.append(float("-inf"))
heap_increase_key(A, heap_size, key)
if __name__ == "__main__":
# list = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
# print list
# heap_increase_key(list, 9, 15)
# print list
list = [15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1]
print list
max_heap_insert(list, 10)
print list