merge sort 主要运用了递归调用的思想,这种排序需要将 list 对半拆分到最小单位,即长度小于等于1,并将最小单位的list分别返回给 left 和 right 。然后通过 merge_sort 函数对其进行排序,将排好序的 list 再进行返回。通过对函数的反复调用,最终实现对 list 的排序。
def merge_split_sort(nums: list) -> list: # 拆分 + 合并
if len(nums) <= 1:
return nums
m = len(nums) // 2
left = merge_split_sort(nums[:m]) # 递归调用
right = merge_split_sort(nums[m:])
return merge_sort(left, right)
def merge_sort(left: list, right: list) -> list: # 排序
c = []
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
c.append(left[0])
left.remove(left[0])
else:
c.append(right[0])
right.remove(right[0])
if len(left) == 0:
c = c + right
else:
c = c + left
return c
def merge_sorted(nums: list, reverse = False):
nums_copy = merge_split_sort(nums)
if reverse:
nums_copy = nums_copy[::-1]
return nums_copy
L = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] # list for test
L = merge_sorted(L, True)
print(L)