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

Merge sort with python

2011-10-09 15:29 218 查看
最近在看《算法导论》,同时又在学习Python,所以想到用PYTHON实现看过的算法,来练手。

PYTHON帮忙看看有没有需要改进的写法

# Suppose the index of current item is i,
# then the parent index is int( (i-1)/2 ),
# the left child index is 2*i+1,
# the right child index is 2*i+2

heap_size = int()
def heapsort(A):
global heap_size
heap_size = 0
build_max_heap(A)
for i  in range(len(A)-1, 0, -1):
# exchange A[0], A[i]
A[0], A[i] = A[i], A[0]
heap_size = heap_size-1
max_heapify(A, 0);

def build_max_heap(A):
global heap_size
heap_size = len(A)
for i in range( int( (len(A)-2)/2 ),-1,-1 ):
max_heapify(A, i)

def max_heapify(A, i):
global heap_size
l = 2*i+1
r = 2*i+2
if l <= heap_size-1 and A[l] > A[i]:
largest = l
else:
largest = i
if r <= heap_size-1 and A[r] > A[largest]:
largest = r
if largest != i:
A[larget], A[i] = A[i], A[largest]
max_heapify(A, i)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: