核心思想:
将一个列表每次二等分,直到每个二等分中中剩下一个元素,然后排序这两个二等分
代码示例:
#-*- coding:utf-8 -*-
def marge(l, r):
results = []
i, j = 0, 0
while i < len(l) and j < len(r):
"确保每一次循环不至于超出两个列表范围"
if l[i] < r[j]:
results.append(r[j])
j += 1
else:
results.append(l[i])
i += 1
while i < len(l):
"将上面循环后剩下的left值加入列表"
results.append(l[i])
i += 1
while j < len(r):
"将上面循环后剩下的right值加入列表"
results.append(r[j])
j += 1
return results
def marge_sort(lists):
if len(lists) < 2:
return lists
else:
middle = int( len(lists) / 2 )
left = marge_sort( lists[ : middle] )
right = marge_sort( lists[middle : ] )
together = marge(left, right)
return together
ls = [3,4,1,2]
print marge_sort( ls )