我正在实现具有反转计数的合并排序。我的代码适用于我的小输入文件(10 个元素),但是当它达到 100000 时,它似乎从粗略搜索返回了不正确的答案。有时更大,有时更小。有人知道吗?
我的代码返回 2402298631。输入文件位置 http://spark-public.s3.amazonaws.com/algo1/programming_prob/IntegerArray.txt
def msort_inv2(m):
global count
if len(m) <= 1:
return m
result = []
middle = int(len(m)/2)
left = msort_inv2(m[:middle])
right = msort_inv2(m[middle:])
while (len(left) > 0) or (len(right) > 0):
if (len(left) > 0) and (len(right) > 0):
if left[0] > right[0]:
result.append(right[0])
count = count + len(left)
right.pop(0)
else:
result.append(left[0])
left.pop(0)
elif len(right) > 0:
for i in right:
result.append(i)
right.pop(0)
else:
for i in left:
result.append(i)
left.pop(0)
return result