The given code is for counting the inversions in the given array or we can say to count the number of changes to be made in an array so that it becomes sorted. Code is working fine for the inputs lower than 10**5 but above that it is giving error and I am unable to solve the error. I also use long long data type where it is required so that it can handle large inputs.
long long merge(long long arr[], int low, int mid, int high){
long long count = 0;
int l1 = mid-low+1;
int l2 = high - mid;
long long arr1[l1];
long long arr2[l2];
for(int i=0;i<l1;i++){
arr1[i] = arr[low+i];
}
for(int i=0;i<l2;i++){
arr2[i] = arr[mid+1+i];
}
int i=0, j=0, k=low;
while(i!=l1 and j!=l2){
if(arr1[i]<arr2[j]){
arr[k++] = arr1[i++];
}
else{
count+=l1-i;
arr[k++] = arr2[j++];
}
}
while(i<l1)
arr[k++] = arr1[i++];
while(j<l2)
arr[k++] = arr2[j++];
return count;
}
long long mergesort(long long arr[], int low, int high){
long long count = 0;
if(low<high){
int mid = (low+high)/2;
count+=mergesort(arr, low, mid);
count+=mergesort(arr, mid+1, high);
count+=merge(arr, low, mid, high);
}
return count;
}
long long solve(long long *arr, int n){
if(n==1) return 0;
return mergesort(arr,0, n);
}