-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSortAdvancedAnalysis.py
64 lines (46 loc) · 1.07 KB
/
InsertionSortAdvancedAnalysis.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
#!/bin/python
import math
import os
import random
import re
import sys
def mergeSort(alist):
inversion_count = 0
n = len(alist)
if n == 1:
return 0
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
n1 = len(lefthalf)
n2 = len(righthalf)
inversion_count += mergeSort(lefthalf)
inversion_count += mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < n1 and j < n2:
if lefthalf[i] <= righthalf[j]:
alist[k] = lefthalf[i]
i = i + 1
else:
alist[k] = righthalf[j]
j = j + 1
inversion_count += n1 - i
k = k + 1
while i < n1:
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < n2:
alist[k] = righthalf[j]
j = j + 1
k = k + 1
return inversion_count
if __name__ == '__main__':
t = int(raw_input())
for t_itr in xrange(t):
n = int(raw_input())
arr = map(int, raw_input().rstrip().split())
result = mergeSort(arr)
print result