编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
#print("Hello world!   -  python.jsrun.net .")
def merge_sort(arr):
    # 基本情况:如果数组只有一个元素或为空,则直接返回
    if len(arr) <= 1:
        return arr

    # 递归地将数组分成两部分
    mid = len(arr) // 2
    print(arr)
    left_half = merge_sort(arr[:mid])
    right_half = merge_sort(arr[mid:])
   
    # 合并两个有序的子数组
    return merge(left_half, right_half)

def merge(left, right):
    sorted_array = []
    left_index = 0
    right_index = 0
    print("left:",left)
    print("right",right)
    # 合并两个子数组,按从小到大的顺序
    while left_index < len(left) and right_index < len(right):
        if left[left_index] < right[right_index]:
            sorted_array.append(left[left_index])
            left_index += 1
        else:
            sorted_array.append(right[right_index])
            right_index += 1

    # 将剩余的元素添加到结果数组中
    sorted_array.extend(left[left_index:])
    sorted_array.extend(right[right_index:])
    print("sort_arry",sorted_array)
    return sorted_array

# 测试
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)