Python 排序算法之堆排序,使用 heapq 实现

"""
堆排序 - 完全二叉树 - 最大堆,最小堆
借助内置的 heapq 模块
"""


def heapsort_use_heap(iterable):
    from heapq import heappush, heappop
    items = []
    for value in iterable:
        heappush(items, value)
    return [heappop(items) for i in range(len(items))]


def test_heapsort():
    import random
    arr = list(range(10))

    random.shuffle(arr)
    print(arr)
    res = heapsort_use_heap(arr)
    print(res)


test_heapsort()
posted @ 2021-03-26 21:23  皎然CEO  阅读(90)  评论(0编辑  收藏  举报