首页 > 文章列表 > python创建和使用堆的方法

python创建和使用堆的方法

Python
379 2022-08-07

1、方法列举

heappush(list, item):向堆中添加一个元素,然后对其重新排序,使其保持堆状态。可用于空列表。

heappop(list):删除第一个(最小的)元素并返回该元素。此操作之后,堆仍然是一个堆,因此我们不必调用heapify()。

heapify(list):将给定的列表变成一个堆。

2、实例

from heapq import heappop, heappush
 
def heap_sort(array):
    heap = []
    for element in array:
        heappush(heap, element)
 
    ordered = []
 
    # While we have elements left in the heap
    while heap:
        ordered.append(heappop(heap))
 
    return ordered
 
array = [13, 21, 15, 5, 26, 4, 17, 18, 24, 2]
print(heap_sort(array))

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。