首页 > 编程语言 > 详细

堆排序

时间:2019-08-18 23:26:43      阅读:147      评论:0      收藏:0      [点我收藏+]
# 堆排序

def max_heap(heap,heapsize,i):
    # 构造最大堆(内部构建)
    left=2*i+1
    right=2*i+2
    larger=i
    if left<heapsize and heap[left]>heap[larger]:
        larger=left
    if right<heapsize and heap[right]>heap[larger]:
        larger=right
    if larger!=i:
        heap[i],heap[larger]=heap[larger],heap[i]
        max_heap(heap,heapsize,larger)

def build_max_heap(heap):
    heapsize=len(heap)
    for i in range((heapsize-1)//2,-1,-1):
        max_heap(heap,heapsize,i)


def heap_sort(heap):
    build_max_heap(heap)
    for i in range(len(heap)-1,-1,-1):
        heap[0],heap[i]=heap[i],heap[0]
        max_heap(heap,i,0)
    return heap

if __name__ == __main__:
    # heap=[3,50,4,29,6,5,1,200,10]
    heap=[6,4,5,2,3,7,1]
    print(heap_sort(heap))

 

堆排序

原文:https://www.cnblogs.com/reyinever/p/11373804.html

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