堆排序 python
Posted 幻觉czw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆排序 python相关的知识,希望对你有一定的参考价值。
# -*- encoding:utf8 -*-
def heapsort(alist):
# 保持最大堆
def max_heapify(alist, idx, size):
left = idx * 2 + 1
right = idx * 2 + 2
length = size
if left < length:
if alist[idx] > alist[left]:
largest = idx
else:
largest = left
if right < length:
if alist[largest] < alist[right]:
largest = right
if left < length and idx != largest:
alist[idx], alist[largest] = alist[largest], alist[idx]
max_heapify(alist, largest, length)
#建最大堆
def build_heap(alist, length):
for i in range((length // 2) - 1, -1, -1):
max_heapify(alist, i, length)
length = len(alist)
build_heap(alist, length)
for i in range(length - 1, 0, -1):
alist[0], alist[i] = alist[i], alist[0]
max_heapify(alist, 0, i)
if __name__ == '__main__':
alist = [7,14,3,5,2,7,6,8,1,0,6,4]
heapsort(alist)
print alist
以上是关于堆排序 python的主要内容,如果未能解决你的问题,请参考以下文章