《算法》-排序[归并排序]

tech2024-10-26  5

归并排序

属于稳定排序

 

步骤:

先(递归地)将数组分成两半,然后把结果归并起来。

def merge(left,right): i,j = 0,0 result = [] while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result def merge_sort(arr): if len(arr) <= 1: return arr num = len(arr)//2 left = merge_sort(arr[:num]) right = merge_sort(arr[num:]) return merge(left,right) if __name__ == "__main__": print(merge_sort([1,23,4,5,34,53]))

公众号:算法手记

最新回复(0)