首先我们先假设有两个有序数组,我们去进行一次归并
用代码实现
def merge(li: list, start: int, mid: int, end: int) : res=[] j = mid +1 while start <= mid and j <= end: if li[start] < li[j]: res.append(li[start]) start +=1 else: res.append(li[j]) j +=1 #运行到这一步,说明左右两边一定有一遍已经下标已经超了,即一定有一遍数字已经没了 #然后判断如果是左边还有数字就把左边剩下的数字全部插入列表中,无需在做判断 #判断如果是右边还有数字就把左边剩下的数字全部插入列表中,无需在做判断 while start <= mid: res.append(li[start]) start +=1 while j <= end: res.append(li[j]) j +=1 return res
最后交给递归
def merge_sort(array): if len(array) == 1: return array left_array = merge_sort(array[:len(array) // 2]) right_array = merge_sort(array[len(array) // 2:]) return merge(left_array, right_array) def merge(left_array, right_array): left_index, right_index, merge_array = 0, 0, list() while left_index < len(left_array) and right_index < len(right_array): if left_array[left_index] <= right_array[right_index]: merge_array.append(left_array[left_index]) left_index += 1 else: merge_array.append(right_array[right_index]) right_index += 1 merge_array = merge_array + left_array[left_index:] + right_array[right_index:] return merge_array