建立堆,保持最大堆,堆排序(顶端最大元素与最后一个元素不断的交换)——整个过程。
#-*-coding:utf-8-*-
def heap_sort(lst):
for start in range((len(lst)-2)/2, -1, -1):
siftdown(lst,start,len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst
def siftdown(lst, start, end):
root = start
while True:
child = 2*root + 1
if child > end:break
if child+1<=end and lst[child] < lst[child+1]:
child += 1
if lst[child] > lst[root]:
lst[child],lst[root] = lst[root],lst[child]
root=child
else:
break
def main():
l=[3,4,1,8,2,9,6,5,7,10]
print heap_sort(l)
if __name__ == '__main__':
main() 使用heapq
#!/usr/bin/env python
#-*-encoding:utf-8-*-
from heapq import heappush,heappop
def heap_sort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]
def main():
L = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print heap_sort(L)
if __name__ == "__main__":
main()