归并排序python实现

时间:2022-12-23 00:11:12
def merge(a,b):
c=[]
h=j=0
while (h<len(a))and(j<len(b)):
if a[h] < b[j]:
c.append(a[h])
h+=1
else:
c.append(b[j])
j+=1
if h==len(a):
for i in b[j:]:
c.append(i)
if j==len(b):
for i in a[h:]:
c.append(i)
return c
def mergesort(arr):
if len(arr)<2:
return arr
middle=len(arr)//2
left=mergesort(arr[:middle])
right=mergesort(arr[middle:])
return merge(left,right)
array=[7,3,5,1,8]
print(mergesort(array))


具体算法解释是:https://blog.csdn.net/qq1137623160/article/details/79610185(有动图,解释的很好)