-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Pairs in an Array.cpp
74 lines (66 loc) · 1.45 KB
/
Count Pairs in an Array.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
// Inversion count
// Time complexity - O(NlogN)
// Space complexity- O(NlogN)
class Solution{
public:
int cnt=0;
void merge(int* arr,int s,int e)
{
int mid=(s+e)/2;
int i=s;
int j=mid+1;
vector<int> temp;
while(i<=mid and j<=e)
{
if(arr[i]>arr[j])
{
temp.push_back(arr[i]);
cnt=cnt+(e-j+1);
i++;
}
else
{
temp.push_back(arr[j]);
j++;
}
}
//copy elements left in left array
while(i<=mid)
{
temp.push_back(arr[i]);
i++;
}
//copy elements left in right array
while(j<=e)
{
temp.push_back(arr[j]);
j++;
}
//copy back to original array
i=s;
for(auto it:temp)
{
arr[i]=it;
i++;
}
}
void mergeSort(int* arr,int s,int e)
{
//base case
if(s>=e)
return ;
//recursive calls
//and small calculation
int mid=(s+e)/2;
mergeSort(arr,s,mid);
mergeSort(arr,mid+1,e);
merge(arr,s,e);
}
int countPairs(int arr[] , int n )
{
for(int i=0;i<n;i++)
arr[i]=i*arr[i];
mergeSort(arr,0,n-1);
return cnt;
}
};