首页 > 编程语言 > 详细

python 堆排序

时间:2018-09-22 10:18:26      阅读:165      评论:0      收藏:0      [点我收藏+]
import copy

 

def heap_sort(hlist):

    def heap_adjust(parent):

        child = 2 * parent + 1  # left child

        while child < len(heap):

            if child + 1 < len(heap):

                if heap[child + 1] > heap[child]:

                    child += 1  # right child

            if heap[parent] >= heap[child]:

                break

            heap[parent], heap[child] = heap[child], heap[parent]

            parent, child = child, 2 * child + 1

 

    heap, hlist = copy.copy(hlist), []

    for i in range(len(heap) // 2, -1, -1):

        heap_adjust(i)

    while len(heap) != 0:

        heap[0], heap[-1] = heap[-1], heap[0]

        hlist.insert(0, heap.pop())

        heap_adjust(0)

    return hlist

 

hlist = heap_sort([4,5,6,7,3,2,6,9,8])

print(hlist)

  

python 堆排序

原文:https://www.cnblogs.com/sea-stream/p/9689056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!