-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount-inversions.py
65 lines (53 loc) · 1.31 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
# Counting inversions using recursion
# Time complexity : O(nlogn)
# D(n) = B(n/2) + C(n/2)
# The split inversions involving an element y
# of 2nd array C are precisely the numbers left in
# the array B when y gets copied to the output D
#
# Reason : Inversion means P[i] > Q[j] where i < j.
# If we have two sorted arrays B and C which are components
# of D, if any element y in C is less than an element in B,
# then y should be less than all the elements in B after that element.
# Hence has split inversion with all those remaining elements in B
from copy import deepcopy
array = [5 , 1, 7, 2, 4, 6, 3, 8]
# array = [1, 2, 3, 4, 5, 6]
count = 0
def merge_countinv(left, right, arr):
global count
nl = len(left)
nr = len(right)
i = 0
j = 0
k = 0
while i < nl and j < nr:
if left[i] < right[j]:
arr[k] = left[i]
i += 1
k += 1
else:
arr[k] = right[j]
j += 1
k += 1
count += len(left[i:len(left)])
while i < nl:
arr[k] = left[i]
i += 1
k += 1
while j < nr:
arr[k] = right[j]
j += 1
k += 1
def merge_sort_countinv(arr):
n = len(arr)
if n == 1:
return
mid = n/2
left_list = deepcopy(arr[:mid])
right_list = deepcopy(arr[mid:n])
merge_sort_countinv(left_list)
merge_sort_countinv(right_list)
merge_countinv(left_list, right_list, arr)
merge_sort_countinv(array)
print count