-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path11. CountInversions.py
57 lines (45 loc) · 1.67 KB
/
11. CountInversions.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
from typing import List
import math
def merge(arr : List[int], low : int, mid : int, high : int) -> int:
temp = [] # temporary array
left = low # starting index of left half of arr
right = mid + 1 # starting index of right half of arr
cnt = 0 # Modification 1: cnt variable to count the pairs
# storing elements in the temporary array in a sorted manner
while (left <= mid and right <= high):
if (arr[left] <= arr[right]):
temp.append(arr[left])
left += 1
else:
temp.append(arr[right])
cnt += (mid - left + 1) # Modification 2
right += 1
# if elements on the left half are still left
while (left <= mid):
temp.append(arr[left])
left += 1
# if elements on the right half are still left
while (right <= high):
temp.append(arr[right])
right += 1
# transfering all elements from temporary to arr
for i in range(low, high + 1):
arr[i] = temp[i - low]
return cnt # Modification 3
def mergeSort(arr : List[int], low : int, high : int) -> int:
cnt = 0
if low >= high:
return cnt
mid = math.floor((low + high) / 2)
cnt += mergeSort(arr, low, mid) # left half
cnt += mergeSort(arr, mid + 1, high) # right half
cnt += merge(arr, low, mid, high) # merging sorted halves
return cnt
def numberOfInversions(a : List[int], n : int) -> int:
return mergeSort(a, 0, n - 1)
if __name__ == "__main__":
a = [5, 4, 3, 2, 1]
n = 5
cnt = numberOfInversions(a, n)
print("The number of inversions are:", cnt)
# Link: https://www.codingninjas.com/studio/problems/number-of-inversions_6840276