-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInversionCounter.py
More file actions
43 lines (35 loc) · 878 Bytes
/
InversionCounter.py
File metadata and controls
43 lines (35 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Count Invertions. By modify merge sort. With time complexity O(nlgn)
# Problems 2-4
__author__ = 'Administrator'
__date__ = '2015.5.25'
def icounter(A, p, q, r, n):
import copy
L = copy.deepcopy(A[p:q])
R = copy.deepcopy(A[q:r])
L.append(float("inf")) # sentinel
R.append(float("inf"))
i = 0
j = 0
l = L.__len__() - 1
for k in range(p, r):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
n = n + l - i
return n
def ICounter(A, p, r, n):
if p < r - 1:
q = (p + r) / 2
n = ICounter(A, p, q, n)
n = ICounter(A, q, r, n)
return icounter(A, p, q, r, n)
return n
def InversionCounter(A):
a = A[:]
return ICounter(a, 0, a.__len__(), 0)
# test
x = [4, 3, 2, 1, 0, 8]
print(InversionCounter(x))