堆排序
Posted reyinever
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆排序相关的知识,希望对你有一定的参考价值。
# 堆排序 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))
以上是关于堆排序的主要内容,如果未能解决你的问题,请参考以下文章