概念
先将数据拆分成最小单元,然后比较大小,组合起来
示意图
代码实现
def merge_sort(lst):
if len(lst) <=1:
return lst
half = len(lst)//2
left_lst = merge_sort(lst[:half])
right_lst = merge_sort(lst[half:])
l_index = 0
r_index = 0
result = []
while l_index < len(left_lst) and r_index < len(right_lst):
if left_lst[l_index] > right_lst[r_index]:
result.append(right_lst[r_index])
r_index += 1
else:
result.append(left_lst[l_index])
l_index += 1
result += left_lst[l_index:]
result += right_lst[r_index:]
return result