arr = [3,4,66,2,1,44,6,5,43,22]
arr1 = [1,3,5,7,2,4,6]
def merge_sort(arr,l,r):
if l < r:
mid = (l + r) // 2
merge_sort(arr,l,mid)
merge_sort(arr,mid+1,r)
merge(arr,l,mid,r)
def merge(arr,l,mid,r): # 合并函数
i = l
j = mid + 1
temp = [] # 存放合并后的数组
while i <= mid or j <= r:
if i <= mid and j <= r:
if arr[i] <= arr[j]:
temp.append(arr[i])
i += 1
else:
temp.append(arr[j])
j += 1
else:
while i <= mid:
temp.append(arr[i])
i += 1
while j <= r:
temp.append(arr[j])
j += 1
arr[l:r+1] = temp[:]
merge_sort(arr,0,len(arr)-1)
arr
输出:
[1, 2, 3, 4, 5, 6, 22, 43, 44, 66]