-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sorting-Merge Sort: Counting Inversions.py
81 lines (57 loc) · 1.47 KB
/
Sorting-Merge Sort: Counting 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#Problem Link : https://www.hackerrank.com/challenges/ctci-merge-sort/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'countInversions' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def sort(a, left, right):
swaps = 0
if right - left == 1:
return swaps
middle = left + ((right - left) // 2)
swaps += sort(a, left, middle)
swaps += sort(a, middle, right)
swaps += merge(a, left, middle, right)
return swaps
def merge(a, left, middle, right):
swaps = 0
buffer = [0] * (right - left)
current = 0
i, j = left, middle
while i < middle and j < right:
if a[i] > a[j]:
buffer[current] = a[j]
j += 1
swaps += middle - i
else:
buffer[current] = a[i]
i += 1
current += 1
while i < middle:
buffer[current] = a[i]
i += 1
current += 1
while j < right:
buffer[current] = a[j]
j += 1
current += 1
a[left:right] = buffer
return swaps
def solve():
n = int(input())
a = list(map(int, input().split()))
return sort(a, 0, n)
def main():
d = int(input())
for _ in range(d):
print(solve())
if __name__ == '__main__':
main()