我试图以不同的方式进行合并排序(而不是文本中可用的那些......),现在我有一个成功的合并算法,但问题是当我递归调用半列表时,合并的东西没有t 得到更新。帮助我处理递归中的可变生命。
下面给出的代码的输出是: -
[9, 5]
After merging [5, 9]
[12, 4]
After merging [4, 12]
[9, 5, 12, 4] #it should be (the updated one i.e [5, 9, 4, 12])
After merging [5, 9, 12, 4]
[6, 8]
After merging [6, 8]
[45, 2]
After merging [2, 45]
[6, 8, 45, 2]
After merging [6, 8, 45, 2]
[9, 5, 12, 4, 6, 8, 45, 2]
After merging [4, 5, 6, 8, 9, 12, 45, 2]
[9, 5, 12, 4, 6, 8, 45, 2]
def merge(arr1, arr2):
"""
Input is two sorted lists
Output is a single merged list
"""
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:
mergeSort(arr[:len(arr)//2])
mergeSort(arr[len(arr)//2:])
print(arr)
arr = merge(arr[:len(arr)//2],arr[len(arr)//2:])
print("After merging", arr)
else:
return arr
a = [9,5,12, 4, 6, 8,45, 2]
mergeSort(a)
print(a)
LEATH
哈士奇WWW
相关分类