- 采用了分治法,把序列不断的等分序列,最后分成一个之后,再把它两两合并叠加起来,利用了扑克牌两个正序序列进行排序合并
- 时间复杂度 nlogn
- 代码
def merge_sort(lists):
if len(lists) <= 1:
return lists
middle = len(lists) // 2
left = merge_sort(lists[:middle])
right = merge_sort(lists[middle:])
return merge(left, right)
def merge(left: list, right: list):
c = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
c.append(left[i])
i += 1
else:
c.append(right[j])
j += 1
if i == len(left):
for i in right[j:]:
c.append(i)
else:
for i in left[i:]:
c.append(i)
return c
if __name__ == '__main__':
list = [1, 5, 2, 3, 8, 9, 10, 11, 12, 14, 14, 7]
print(merge_sort(list))
标签:__,归并,right,python,lists,merge,len,排序,left From: https://www.cnblogs.com/sardine96/p/17001629.html