!/usr/bin/python
'''file name: inversion.py
--P41
--calculate the inversion number in nlgn for the worse situation
--author: zevolo, 2012.05.07
'''
global count
def merge_sort(list, s, e):
global count
if e == s:
return
m = (e + s) / 2
#print "sort %d-->%d call %d, %d %d, %d" % (s, e, s, m, m+1, e)
merge_sort(list, s, m)
merge_sort(list, m + 1, e)
l = list[s : m+1]
r = list[m+1 : e+1]
p1 = 0
p2 = 0
for i in range(s, e+1):
if p1 >= (m + 1 - s):
list[i] = r[p2]
p2 += 1
elif p2 >= (e - m):
list[i] = l[p1]
p1 += 1
count += 1
elif l[p1] <= r[p2]:
list[i] = l[p1]
p1 += 1
else:
list[i] = r[p2]
p2 += 1
count += 1
if __name__ == '__main__':
global count
count = 0
l = [0, 3, 1, 9,7,5,2,8, 10,6,4,11]
merge_sort(l, 0, len(l) - 1)
print l
print "count is %d" % (count,)
计算逆序对的个数
最新推荐文章于 2023-11-21 22:27:10 发布