*Your* program works as you expect.
Code:

#if 0
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Tue Jul 2 19:34:39
a=./c && make -k $a && $a
cc -Wall -g c.c -o c
2 4 1 3 5
INVERSIONS: 3
1 2 3 4 5
Compilation finished at Tue Jul 2 19:34:39
#endif
#include<stdlib.h>
#include<stdio.h>
#define DIM(A) (sizeof((A))/sizeof(*(A)))
int merge(int arr[], int temp[], int left, int mid, int right) {
int i, j, k;
int inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* i is index for right subarray*/
k = left; /* i is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right))
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else {
temp[k++] = arr[j++];
inv_count = inv_count + (mid - i);
}
/* Copy the remaining elements of left subarray (if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray (if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i=left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
int mergesort(int arr[], int temp[], int left, int right) {
int mid;
int inv_count = 0;
if (right > left) {
mid = (right + left)/2;
inv_count = mergesort(arr, temp, left, mid);
inv_count += mergesort(arr, temp, mid+1, right);
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
int mergeSort(int arr[], int array_size) {
int *temp = (int *)malloc(sizeof(int)*array_size);
return mergesort(arr, temp, 0, array_size - 1);
}
void display(int*a,int n) {
int i;
for (i = 0; i < n; ++i)
printf("%3d",a[i]);
putchar('\n');
}
int a[] = {2,4,1,3,5};
int main() {
display(a, DIM(a));
printf("INVERSIONS: %d\n",mergeSort(a,DIM(a)));
display(a, DIM(a));
return 0;
}

Tweet This+ 1 thisPost To Linkedin