"""
归并排序 — 分治法的经典应用
时间复杂度 O(n log n)，空间复杂度 O(n)
"""

def merge(arr, left, mid, right):
    """合并两个有序子数组"""
    # 创建临时数组
    L = arr[left:mid + 1]
    R = arr[mid + 1:right + 1]

    i = j = 0
    k = left

    # 合并两个有序数组
    while i < len(L) and j < len(R):
        if L[i] <= R[j]:
            arr[k] = L[i]
            i += 1
        else:
            arr[k] = R[j]
            j += 1
        k += 1

    # 复制剩余元素
    while i < len(L):
        arr[k] = L[i]
        i += 1
        k += 1
    while j < len(R):
        arr[k] = R[j]
        j += 1
        k += 1

def merge_sort(arr, left, right):
    """归并排序主函数"""
    if left < right:
        mid = (left + right) // 2
        merge_sort(arr, left, mid)
        merge_sort(arr, mid + 1, right)
        merge(arr, left, mid, right)

def sort(arr):
    merge_sort(arr, 0, len(arr) - 1)

if __name__ == "__main__":
    data = [38, 27, 43, 3, 9, 82, 10]
    print("排序前:", data)
    sort(data)
    print("排序后:", data)
