-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Inversions-GFG.cpp
84 lines (67 loc) · 1.77 KB
/
Count Inversions-GFG.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
74
75
76
77
78
79
80
81
82
83
84
// TC->O(NlogN)
// SC->O(N)
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// arr[]: Input Array
// N : Size of the Array arr[]
// Function to count inversions in the array.
long long int merge(long long arr[], long long first, long long mid, long long last){
long long int count=0;
vector<long long> temp;
long long i=first, j=mid+1;
while(i<=mid && j<=last){
if(arr[i]>arr[j]){
temp.push_back(arr[j++]);
count=count+(mid-i)+1;
}else{
temp.push_back(arr[i++]);
}
}
while(i<=mid){
temp.push_back(arr[i++]);
}
while(j<=last){
temp.push_back(arr[j++]);
}
i=0;
while(first<=last){
arr[first++]=temp[i++];
}
return count;
}
long long int mergeSort(long long arr[], long long first, long long last){
long long int count=0;
if(first<last){
long long mid=first+(last-first)/2;
count+=mergeSort(arr,first,mid);
count+=mergeSort(arr,mid+1,last);
count+=merge(arr,first,mid,last);
}
return count;
}
long long int inversionCount(long long arr[], long long N)
{
return mergeSort(arr,0,N-1);
}
};
//{ Driver Code Starts.
int main() {
long long T;
cin >> T;
while(T--){
long long N;
cin >> N;
long long A[N];
for(long long i = 0;i<N;i++){
cin >> A[i];
}
Solution obj;
cout << obj.inversionCount(A,N) << endl;
}
return 0;
}
// } Driver Code Ends