-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-merge-sort-count-inversions.py
52 lines (42 loc) · 1.27 KB
/
2-merge-sort-count-inversions.py
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
inversions = 0
def count_inversions(num_list):
global inversions
middle = int(len(num_list) / 2)
left = num_list[:middle]
right = num_list[middle:]
if len(num_list) > 1:
count_inversions(left)
count_inversions(right)
i = 0
j = 0
m = left
n = right
for k in range(len(m) + len(n) + 1):
if m[i] <= n[j]:
num_list[k] = m[i]
i += 1
if i == len(m) and j != len(n):
while j != len(n):
k += 1
num_list[k] = n[j]
j += 1
break
elif m[i] > n[j]:
num_list[k] = n[j]
inversions += (len(m) - i)
j += 1
if j == len(n) and i != len(m):
while i != len(m):
k += 1
num_list[k] = m[i]
i += 1
break
file = open("D:\\Algorithms-Specialization\\files\\merge_sort_integers.txt")
lines = file.readlines()
file.close()
num_array = []
for n in range(0, len(lines)):
lines[n] = lines[n].strip()
num_array.append(int(lines[n]))
count_inversions(num_array)
print(inversions)