默认的 heapq 是最小队列实现,我想知道是否有最大队列的选项?谢谢。
我尝试了使用 _heapify_max 实现最大堆,但如何处理动态推入/弹出元素呢?似乎 _heapify_max 只能在初始化时使用。
import heapq
def heapsort(iterable):
h = []
for value in iterable:
heapq.heappush(h, value)
return [heapq.heappop(h) for i in range(len(h))]
if __name__ == "__main__":
print heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
编辑,尝试使用_heapify_max似乎不能动态推入/弹出元素。我尝试了两种方法,输出结果相同,都是 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]。
def heapsort(iterable):
h = []
for value in iterable:
heapq.heappush(h, value)
return [heapq.heappop(h) for i in range(len(h))]
def heapsort2(iterable):
h = []
heapq._heapify_max(h)
for value in iterable:
heapq.heappush(h, value)
return [heapq.heappop(h) for i in range(len(h))]
if __name__ == "__main__":
print heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print heapsort2([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
提前感谢,Lin