def count(array):
def merge(l,r):
if len(l) == 0 or len(r) == 0:
return (l+r,0)
#print l,r
n = 0
res = []
j,k = 0,0
lengthl = len(l)
lengthr = len(r)
for i in xrange(len(l + r)):
if l[j] < r[k]:
res.append(l[j])
#print "left",l[j]
j += 1
else:
#print r[k]
res.append(r[k])
k += 1
num = lengthl - j
n += num
if j == lengthl:
for ex in xrange(k,lengthr):
#n += 1
res.append(r[ex])
return (res,n)
if k == len(r):
for ex in xrange(j,lengthl):
res.append(l[ex])
return (res,n)
return (res,n)
if len(array) <= 1:
return (array,0)
left , a = count(array[: len(array) / 2])
right , b = count(array[len(array) / 2:])
combine , c = merge(left ,right)
#print a,b,c
return (combine,a + b + c)
f = open("IntegerArray.txt")
a = []
for line in f:
a.append(int(line))
print count(a)[1]
f.close()
count inversion
最新推荐文章于 2021-08-11 22:33:41 发布