归并排序_Python

def merge_sort(array):
    if len(array) == 1:
        return array
    middle_index = len(array) // 2
    left = merge_sort(array[:middle_index])
    right = merge_sort(array[middle_index:])
    return merge_comb(left, right)


def merge_comb(left, right):
    comb_list = []
    while left and right:
        if left[0] <= right[0]:
            comb_list.append(left.pop(0))
        else:
            comb_list.append(right.pop(0))
    while left:
        comb_list.append(left.pop(0))
    while right:
        comb_list.append((right.pop(0)))
    return comb_list


my_list = [5, 8, 6, 3, 9, 2, 1, 7]
print(merge_sort(my_list))

猜你喜欢

转载自blog.csdn.net/goodlmoney/article/details/121368670