Unusual garbage value answers in SPOJ question INVCNT solution

I was solving this question: INVCNT on SPOJ.

I simply implemented the Merge Sort variant that counts inversions as well: First solution.

This returns a correct solution for the all the test cases I could think of, but then I realized that inversions could go beyond 10^8, so I changed this implementation to use long long instead.
Second solution

Now weirdly, this solution returns a different value every time I execute it. I have initialized all variables. For example, trying this test case:

1

5
5
4
3
2
1

The answer should be 10, and the int solution does get this correct, but the long long solution keeps changing its answer every time I execute it. It usually gives answers in the range 13, 14, 15

I am fairly new to C++, please help me debug this. Is my solution correct? Why is the value changing every time even though the variables seem to be initialized?

Thanks for the help! :slight_smile:

I’m using GCC version 6.2.1 on linux if it matters.

Array index out of bounds. Check what is happening in the loop in MergeCount if lptr==m or rptr==n.