码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2019-08-18 21:27:15      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:range   堆排   EAP   build   def   turn   code   name   i+1   

# 堆排序

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))

 

堆排序

标签:range   堆排   EAP   build   def   turn   code   name   i+1   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!