def merge(arr,l,m,r,temp):
k = l
i = l
j = m+1
while i<m+1 and j<r+1:
if arr[i]<arr[j]:
temp[k]=arr[i]
i+=1
else:
temp[k]=arr[j]
j+=1
k+=1
#将左右两边剩余的数字直接加入到temp数组中
while i<m+1:
temp[k]=arr[i]
i+=1
k+=1
while j<r+1:
temp[k]=arr[j]
j+=1
k+=1
#注意更新arr数组的值,不更新则前面的排序都没有用了呢!
for i in range(l,r+1):
arr[i]=temp[i]
def mergeSort(arr,l,r,temp):
if l<r:
mid = (l + r) // 2
mergeSort(arr,l,mid,temp)
mergeSort(arr,mid+1,r,temp)
merge(arr,l,mid,r,temp)
print(f"l={l},m={mid},r={r}")
print(temp)
arr=[7,4,8,4,2,5,10,1]
n=len(arr)
temp=[0]*n
mergeSort(arr,0,n-1,temp)
print(temp)
想写没有temp数组的可以参考菜鸟教程
https://www.runoob.com/python3/python-merge-sort.html
它这个是创建了两个新数组来标记左右数组的
我使用的是temp数组来记录排列好的数字
要注意每次合并后要更新arr数组的值,不能让排列好的数字只停留在temp数组中