归并排序(python实现)
def mergesort(L):
print L
if len(L)<2:
return L[:]
else:
middle=len(L)/2
left=mergesort(L[:middle])
right=mergesort(L[middle:])
together=merge(left,right)
print 'left' ,left
print 'right',right
print 'merge',together
return together
def merge(left,right):
result=[]
i,j=0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
while (i<len(left)):
result.append(left[i])
i=i+1
while (j<len(right)):
result.append(right[j])
j=j+1
return result
最近在看MIT的计算机科学与编程导论,这是其中的一个小例子,中午照着代码调试了好久,才知道是如何运行的。哎,真失败!
坚持就是胜利!