'Finding number of inversions in given array

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


Solution 1:[1]

I am very interested in C++ so I am learning it. It's already 1 year learning C++ so I think I could help you. You Have many mistakes but I noticed The actual mistake It's the actual output. I used this code only in educational purposes and that's the mistake. Your actual output is not correct The actual actual output is: 2 1 4 2 5 264755412

So you can check again your code to see your mistake. Best REGARDS from Tigran. Country: Armenia | Region: Yerevan

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tigran From Armenia