2 回答
TA贡献1936条经验 获得超6个赞
我只做了很小的改变,所以代码仍然是你的努力,你是如此接近,看看:
问题是,在查看您的代码后,您必须将两半传递给合并方法,并检查它是否为空。此外,返回结果而不是进行原地更改要好得多-
def merge(arr1, arr2):
for i in arr1:
for j in list(range(len(arr2))):
if i<arr2[j]:
arr2.append(arr2[-1])
for count in list(range(len(arr2)-1, j, -1)):
arr2[count] = arr2[count-1]
arr2[j] = i
break
if j == len(arr2)-1:
arr2.append(i)
return arr2
def mergeSort(arr):
if len(arr) !=1 and len(arr):
ary1 = mergeSort(arr[:len(arr)//2])
ary2 = mergeSort(arr[len(arr)//2:])
print(arr)
ary3 = merge(ary1,ary2)
print("After merging", ary3)
return ary3
else:
return arr
a = [9,5,12, 4, 6, 8,45, 2]
print(mergeSort(a))
输出
[9, 5]
After merging [5, 9]
[12, 4]
After merging [4, 12]
[9, 5, 12, 4]
After merging [4, 5, 9, 12]
[6, 8]
After merging [6, 8]
[45, 2]
After merging [2, 45]
[6, 8, 45, 2]
After merging [2, 6, 8, 45]
[9, 5, 12, 4, 6, 8, 45, 2]
After merging [2, 4, 5, 6, 8, 9, 12, 45]
[2, 4, 5, 6, 8, 9, 12, 45]
TA贡献1799条经验 获得超6个赞
你应该mergeSort返回合并的列表,调用者应该输出返回值mergeSort:
def merge(arr1, arr2):
merged = []
while arr1 and arr2:
if arr1[0] > arr2[0]:
arr1, arr2 = arr2, arr1
merged.append(arr1.pop(0))
merged.extend(arr1 or arr2)
return merged
def mergeSort(arr):
if len(arr) <= 1:
return arr
return merge(mergeSort(arr[:len(arr)//2]), mergeSort(arr[len(arr)//2:]))
a = [9, 5, 12, 4, 6, 8, 45, 2]
print(mergeSort(a))
添加回答
举报