我已经实现了合并排序,除了排序之外,我还希望它计算原始数组中的反转数。
下面是我实现它的尝试,由于某种原因,它不能正确计算反转的数量。
例如,mergeSort([4, 3, 2, 1])
应该返回(6, [1, 2, 3, 4])
.
def mergeSort(alist):
count = 0
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
count +=len(lefthalf[i:])
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
return count, alist