概念
归并排序是利用归并的思想实现的排序方法,该算法采用了经典的分治(divide-and-conquer)策略(分治法讲问题分成一些小的问题然后递归求解,而治的阶段则讲分的阶段的答案合并到一起,即分而治之)。
过程
code
def merge(left, right):
result = []
left_idx = right_idx = 0
left_over = False
while True:
if left[left_idx] < right[right_idx]:
result.append(left[left_idx])
left_idx += 1
else:
result.append(right[right_idx])
right_idx += 1
if left_idx >= len(left):
left_over = True
break
elif right_idx >= len(right):
break
if left_over:
for item in right[right_idx:]:
result.append(item)
else:
for item in left[left_idx:]:
result.append(item)
return result
def merge_sort(l):
if len(l) <= 1:
return l
mid_idx = len(l) / 2
left = merge_sort(l[:mid_idx])
right = merge_sort(l[mid_idx:])
return merge(left, right)
Test
def test():
l = [4, 7, 8, 3, 5, 9, 9, 9, 0, 7, 4, 3, 1, 6]
print l
print merge_sort(l)