AcWing 787. 归并排序 简单Python实现
原题链接
简单
作者:
皓首不倦
,
2020-08-06 18:59:05
,
所有人可见
,
阅读 420
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = (len(arr)-1) // 2
arr1 = merge_sort(arr[:mid+1])
arr2 = merge_sort(arr[mid+1:])
ans = []
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
ans.append(arr1[i])
i += 1
else:
ans.append(arr2[j])
j += 1
if i < len(arr1):
ans.extend(arr1[i:])
else:
ans.extend(arr2[j:])
return ans
n = int(input())
data = list(map(int, input().split()))
data = merge_sort(data)
print(' '.join(map(str, data)))