#include <stdio.h>
#include<stdlib.h>
static void merge(int *array, int start, int mid, int end, int *count){
int *leftarray = (int *)calloc(sizeof(int), mid-start+2);
int *rightarray = (int *)calloc(sizeof(int), end-mid+2);
int i,j = 0,k=0;
for (i = start; i <= mid; i++){
leftarray[j++] = array[i];
}
leftarray[j] = 2147483647;
j = 0;
for (i = mid + 1; i <= end; i++){
rightarray[j++] = array[i];
}
rightarray[j] = 2147483647;
j = 0;
for (i = start; i <= end; i++){
if (leftarray[j] <= rightarray[k]){
array[i] = leftarray[j];
j++;
}
else {
array[i] = rightarray[k];
k++;
if (i != end){
*count += mid + 1 - start - j;
}
}
}
}
static void display(int *array, int size){
for (int i = 0; i<size; i++){
printf("%d ", array[i]);
}
printf("\n");
}
static void mergeSort(int *array, int start, int end, int *count){
if (start >= end){
return;
}
int mid = (start + end) / 2;
mergeSort(array, start, mid, count);
mergeSort(array, mid + 1, end, count);
merge(array, start, mid, end, count);
}
int mergesort() {
int n;
long long int count = 0;
//scanf("%d", &n);
int * array = (int *)calloc(sizeof(int), 100005);
int number = 199999;
for (int i = 0; i < 100000; i++){
array[i] = number--;
}
/*for (int i=0; i<n; i++){
scanf("%d", &array[i]);
}*/
mergeSort(array, 0, 100000 - 1, &count);
/*display(array, n);*/
printf("%d\n", count);
return 0;
}
int main(){
mergesort();
return 0;
}
I am trying to solve this problem from geeksforgeeks (https://www.geeksforgeeks.org/counting-inversions/) and implemented the following code but it gives wrong result for the above input values the reverse sorted array from 199999 to 100000 instead of getting result as 4999950000 i am getting some other result i tried debugging but it was useless can anyone tell me where did i go wrong