-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinversion_count.cpp
More file actions
56 lines (43 loc) · 994 Bytes
/
Copy pathinversion_count.cpp
File metadata and controls
56 lines (43 loc) · 994 Bytes
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
//Problem Link : https://www.hackerrank.com/challenges/ctci-merge-sort/problem
//Most efficient Solution :
#include<iostream>
using namespace std;
long long merge(int A[],int left,int mid,int right){
int i=left,j=mid,k=0;
int temp[right-left+1];
long long count = 0;
while(i<mid && j<=right){
if(A[i] <= A[j]){
temp[k++] = A[i++];
}else{
temp[k++] = A[j++];
count += mid - i;
}
}
while(i<mid){
temp[k++] = A[i++];
}
while(j<=right){
temp[k++] = A[j++];
}
for(int i=left,k=0;i<=right;i++,k++){
A[i] = temp[k];
}
return count;
}
long long merge_sort(int A[],int left,int right){
long long count = 0;
if(right > left){
int mid = (left + right)/2;
long long countLeft = merge_sort(A,left,mid);
long long countRight = merge_sort(A,mid+1,right);
long long myCount = merge(A,left,mid+1,right);
return myCount + countLeft + countRight;
}
return count;
}
long long solve(int A[], int n)
{
long long ans = merge_sort(A,0,n-1);
return ans;
}