forked from veeru-jk/Algorithms-In-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01) Array inversions.py
More file actions
77 lines (60 loc) · 1.66 KB
/
01) Array inversions.py
File metadata and controls
77 lines (60 loc) · 1.66 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'''
Algorithms - design and analysis (Stanford), Part I.
Programming assignment 1:
count the number of inversions
in the given list in O(n*log(n)).
@author: Mikhail Dubov
'''
def _SortAndCountInversions(lst, start, end):
'''
To count inversions, we just use
a slightly modified version of MergeSort.
'''
if (start == end):
return 0
else:
x = _SortAndCountInversions(lst, start, (end+start)//2)
y = _SortAndCountInversions(lst, (end+start)//2+1, end)
z = _MergeAndCountSplitInversions(lst, start, (end+start)//2+1, end)
return (x+y+z)
def _MergeAndCountSplitInversions(lst, start, m, end):
i = start
j = m
res = []
inv = 0
while (i < m or j <= end):
if (i == m):
res.append(lst[j])
j += 1
elif (j > end):
res.append(lst[i])
i += 1
elif (lst[i] <= lst[j]):
res.append(lst[i])
i += 1
else:
inv += (m-i) # Split inversions discovered
res.append(lst[j])
j += 1
i = start
while (i <= end):
lst[i] = res[i-start]
i += 1
return inv
def CountInversions(lst):
return _SortAndCountInversions(lst, 0, len(lst)-1)
def main():
# Test
print(CountInversions([1,2,3,4,5,6]))
print(CountInversions([6,5,4,3,2,1]))
print(CountInversions([1,3,5,2,4,6]))
# Assignment data
f = open('IntegerArray.txt', 'r')
lst = []
line = f.readline()
while (line != ''):
lst.append(int(line))
line = f.readline()
print(CountInversions(lst))
if __name__ == '__main__':
main()