您的位置:首页 > 编程语言 > Python开发

算法导论堆排序python实现

2015-03-09 00:03 232 查看
#-*-coding:utf-8-*-
def max_heap(A, i, heapsize):
largest = -1
while True:

left = 2*i+1
right = 2*i + 2
if left<heapsize and A[i]<A[left]:
largest=left
else:
largest=i
if right<heapsize and A[largest]<A[right]:
largest=right
if largest  is not i:
A[largest],A[i] = A[i],A[largest]
i=largest
else:
break
def build_max_heap(A):
n = len(A)
for i in range(int(n/2)-1,-1,-1):
max_heap(A, i, n)
def heap_sort(A):
build_max_heap(A)
n = len(A)
for i in range(n-1,-1,-1):
A[0],A[i]=A[i],A[0]
max_heap(A,0, i)
A=[1,3,8,6,1,4,6,4,0]
heap_sort(A)
print A
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: