python创建和使用堆的方法

Python (182) 2023-05-04 14:14:13

1、方法列举

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

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

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

2、实例

fromheapqimportheappop,heappush

defheap_sort(array):
heap=[]
forelementinarray:
heappush(heap,element)

ordered=[]

#Whilewehaveelementsleftintheheap
whileheap:
ordered.append(heappop(heap))

returnordered

array=[13,21,15,5,26,4,17,18,24,2]
print(heap_sort(array))

以上就是python创建和使用堆的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

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

THE END

发表回复