Skip to content

Commit 572daf2

Browse files
Added count inversions in cpp
1 parent 0ebc31f commit 572daf2

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Count Inversions:
2+
Given an array of integers. Find the Inversion Count in the array.
3+
4+
Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then the inversion count is 0.
5+
If an array is sorted in the reverse order then the inversion count is the maximum.
6+
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
7+
8+
9+
Example 1:
10+
11+
Input: N = 5, arr[] = {2, 4, 1, 3, 5}
12+
Output: 3
13+
Explanation: The sequence 2, 4, 1, 3, 5
14+
has three inversions (2, 1), (4, 1), (4, 3).
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
// } Driver Code Ends
6+
class Solution{
7+
public:
8+
// arr[]: Input Array
9+
// N : Size of the Array arr[]
10+
// Function to count inversions in the array.
11+
long long merge(long long arr[], long long temp[], long long left, long long mid, long long right){
12+
long long i, j, k;
13+
long long inv_count = 0;
14+
15+
i = left;
16+
j = mid;
17+
k = left;
18+
19+
while(( i <= mid - 1)&&( j <= right )){
20+
if(arr[i] <= arr[j]){
21+
temp[k++] = arr[i++];
22+
}
23+
else{
24+
temp[k++] = arr[j++];
25+
26+
inv_count = inv_count + (mid - i);
27+
}
28+
}
29+
30+
while( i <= mid - 1)
31+
temp[k++] = arr[i++];
32+
while( j <= right )
33+
temp[k++] = arr[j++];
34+
35+
for(i = left; i <= right; i++ ){
36+
arr[i] = temp[i];
37+
}
38+
39+
return inv_count;
40+
}
41+
42+
long long mergesort( long long arr[], long long temp[], long long left, long long right){
43+
long long mid, inv_count = 0;
44+
45+
if(right > left){
46+
47+
mid = (left + right)/2;
48+
49+
inv_count += mergesort(arr, temp, left, mid);
50+
inv_count += mergesort(arr, temp, mid + 1, right);
51+
52+
inv_count += merge(arr, temp, left, mid + 1, right);
53+
}
54+
55+
return inv_count;
56+
}
57+
58+
long long inversionCount(long long arr[], long long N)
59+
{
60+
long long temp[N];
61+
long long ct = mergesort(arr, temp, 0, N - 1);
62+
return ct;
63+
}
64+
65+
};
66+
67+
// { Driver Code Starts.
68+
69+
int main() {
70+
71+
long long T;
72+
cin >> T;
73+
74+
while(T--){
75+
long long N;
76+
cin >> N;
77+
78+
long long A[N];
79+
for(long long i = 0;i<N;i++){
80+
cin >> A[i];
81+
}
82+
Solution obj;
83+
cout << obj.inversionCount(A,N) << endl;
84+
}
85+
86+
return 0;
87+
}
88+
// } Driver Code Ends

0 commit comments

Comments
 (0)