forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount inversion
61 lines (51 loc) · 1.52 KB
/
count inversion
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
#include <bits/stdc++.h>
void merge(long long arr[],long long int st,long long int mid,long long int end,long long int &count){
int i=st;int j=mid+1;
vector<int>dummy;
while(i<=mid || j<=end){
if(i<=mid && j<=end){
if(arr[i]<=arr[j]){
dummy.push_back(arr[i]);
i++;
}
else {
count=count+(mid+1-i);
// count++;
dummy.push_back(arr[j]);
j++;
}
}
else if(i<=mid){
dummy.push_back(arr[i]);
i++;
}
else if(j<=end){
dummy.push_back(arr[j]);
j++;
}
}
int x=0;
for(long long int i=st;i<=end;i++){
arr[i]=dummy[x];x++;
}
return;
}
void mergesort(long long arr[],long long n,long long st,long long en,long long int &count){
if(st==en){
return;
}
else{
long long int mid=(st+en)/2;
mergesort(arr,n,st,mid,count);
mergesort(arr,n,mid+1,en,count);
merge(arr,st,mid,en,count);
return;
}
}
long long int inversionCount(long long arr[], long long N)
{
// Your Code Herevoid
long long int count=0;
mergesort(arr,N,0,N-1,count);
return count;
}