-
Notifications
You must be signed in to change notification settings - Fork 0
/
Inversions.cpp
73 lines (56 loc) · 1.14 KB
/
Inversions.cpp
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
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
long int merge(long int a[],long int l,long int r,long int mid,long int n);
long int mergesort(long int a[],long int l,long int r,long int n)
{
long int mid;long int inv_count=0;
if(l<r)
{
mid=(l+r)/2;
inv_count+=mergesort(a,l,mid,n);
inv_count+=mergesort(a,mid+1,r,n);
inv_count+=merge(a,l,r,mid+1,n);
}
return inv_count;
}
long int merge(long int a[],long int l,long int r,long int mid,long int n)
{
int temp[n];long int i,j,k;long int inv_count=0;
i=l;
j=mid;
k=l;
while((i<=mid-1) && (j<=r))
{
if(a[i]<=a[j])
temp[k++]=a[i++];
else
{
temp[k++]=a[j++];
inv_count+=mid-i;
}
}
//remaining elements
while(i<=mid-1)
temp[k++]=a[i++];
while(j<=r)
temp[k++]=a[j++];
for(int i=l;i<=r;i++)
a[i]=temp[i];
return inv_count;
}
int main() {
//code
int t;
cin>>t;
while(t-->0)
{
long int n;
cin>>n;
long int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
cout<<mergesort(a,0,n-1,n)<<endl;
}
return 0;
}