I have written the following code to find the inversions in array {1,4,2,5,3} by using merge sort technique. I have been debugging it to the best of my knoledge but I am not able to find out my mistake (as the output is not expected). Kindly help.
Please note: this is done for educational purposes and is not part of any ongoing contest.
My code:
#include<iostream>
#include<vector>
using namespace std;
int merge(int *arr,int l,int m,int r,int n)
{
int temp[n];
long long count =0;
int i=l;
int j=m+1;
while(i<=m and j<=r)
{
if (arr[i-1]>arr[j-1])
{
count += m-i+1;
temp[i+j-m-2] = arr[j-1];
j++;
}
else
{
temp[i+j-m-2] = arr[i-1];
i++;
}
}
if (i>m)
{
for (int k=j;k<=r;k++)
temp[k-1] = arr[k-1];
}
else
{
for (int k=i;k<=m;k++)
temp[k-1] = arr[k-1];
}
for (int k=l;k<=r;k++)
arr[k-1] = temp[k-1];
return count;
}
int inversions(int *arr, int l,int r,int n)
{
if (l<r)
{
int m=(l+r)/2;
return inversions(arr,l,m,n)+inversions(arr,m+1,r,n)+merge(arr,l,m,r,n);
}
return 0;
}
int main()
{
int arr[5] = {1,4,2,5,3};
cout<<inversions(arr,1,5,5)<<endl;
for (int i=1;i<=5;i++)
cout<<arr[i-1]<<" ";
return 0;
}
My expected output:
3
1 2 3 4 5
Actual output
2
1 4 2 5 0