-
Notifications
You must be signed in to change notification settings - Fork 892
/
problem_044.py
47 lines (36 loc) · 1.06 KB
/
problem_044.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
def merge(a_with_inv, b_with_inv):
i, k = 0, 0
merged = list()
a, a_inv = a_with_inv
b, b_inv = b_with_inv
inversions = a_inv + b_inv
while i < len(a) and k < len(b):
if a[i] < b[k]:
merged.append(a[i])
i += 1
else:
merged.append(b[k])
inversions += len(a[i:])
k += 1
while i < len(a):
merged.append(a[i])
i += 1
while k < len(b):
merged.append(b[k])
k += 1
return merged, inversions
def merge_sort(arr):
if not arr or len(arr) == 1:
return arr, 0
mid = len(arr) // 2
merged_array, inversions = merge(
merge_sort(arr[:mid]), merge_sort(arr[mid:]))
return merged_array, inversions
def count_inversions(arr):
_, inversions = merge_sort(arr)
return inversions
assert count_inversions([1, 2, 3, 4, 5]) == 0
assert count_inversions([2, 1, 3, 4, 5]) == 1
assert count_inversions([2, 4, 1, 3, 5]) == 3
assert count_inversions([2, 6, 1, 3, 7]) == 3
assert count_inversions([5, 4, 3, 2, 1]) == 10