我在 pyhton 中制作了一个计数反转程序,并使用 python27 来实现。我已经使用分而治之的技术(合并排序技巧)实现了算法。我的程序对于大小为 100 的输入数组运行良好(这是我可以验证的最大值)。现在我在大小为 50,000 和 1,00,000 的输入数组上测试了我的程序,但是我怎么也无法得到正确的答案。我在下面粘贴了我的代码,请指出任何可能的错误:
f=open('forum.txt')
a=[]
s=1
for line in f:
a.append(line)
def CountInversion(IntegerArray):
_count=0
lc=0
rc=0
RightArray=[]
LeftArray=[]
if len(IntegerArray)>1:
LeftArray,lc=CountInversion(IntegerArray[:len(IntegerArray)/2])
RightArray,rc=CountInversion(IntegerArray[len(IntegerArray)/2:])
elif len(IntegerArray)==1:
return IntegerArray,0
ResultArray=IntegerArray
i=0
l=len(ResultArray)
j,k=0,0
for i in range(0,l):
if j<len(RightArray) and k<len(LeftArray):
if RightArray[j]<LeftArray[k]:
ResultArray[i]=RightArray[j]
j += 1
a=(len(LeftArray)-k)
_count = _count + a
else:
ResultArray[i]=LeftArray[k]
k += 1
elif j<len(RightArray):
ResultArray[i]=RightArray[j]
j += 1
elif k<len(LeftArray):
ResultArray[i]=LeftArray[k]
k += 1
return ResultArray,(_count+lc+rc)
arr,b=CountInversion(a)
print ('end of inversions')
print b
我还运行了 JF Sebastian 在这篇文章中给出的代码,但结果是相同的(答案对于小输入是正确的,但对于大小为 50000 或 1,00,000 的输入数组则不正确)