2025年01月14日 建站教程
由于在python中堆的特性是最小堆,堆顶的元素始终是最小的,可以将序列转换成堆之后,再使用pop弹出堆顶元素来实现从小到大排序。具体实现代码如下:
from heapq import heappush, heappop, heapify
def heapsort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]
def heapsort2(iterable):
heapify(iterable)
return [heappop(iterable) for i in range(len(iterable))]
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print(heapsort(data))
print(heapsort2(data))
#输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
本文链接:http://so.lmcjl.com/news/21304/