why is the following programme incorrect for finding the number of inversions in an array. To know about inversions google it. for all small inputs that i could devise, i got a correct answer. however for this input of size 100,000 the answer differs from original. The code is:-
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll counts=0;
void stitchncount(ll *,ll *,ll *,ll ,ll );
void mergencount(ll *,ll );
int main()
{
ll n;
cout<<"enter the number of elements in the array"<<endl;
cin>>n;
ll * arr;
arr=new ll[n];
for(ll i=0;i<n;i++)
{
cin>>arr[i];
}
mergencount(arr,n);
cout<<"the number of inversions are "<<counts<<endl;
return 0;
}
void stitchncount(ll *arr,ll *arr1,ll *arr2,ll sizedh1,ll sizedh2)
{
ll sized1,sized2;
sized1=sizedh1;
sized2=sizedh2;
ll i,j,k;
i=j=k=0;
while(i<sized1 && j<sized2)
{
if(arr1[i]<arr2[j])
{
arr[k]=arr1[i];
i++;
}
else
{
arr[k]=arr2[j];
j++;
counts+=(sized1-i);
}
k++;
}
if(i==sized1)
{
arr[k]=arr2[j];
j++;
k++;
}
else
{
arr[k]=arr1[i];
i++;
k++;
}
}
void mergencount(ll * arr, ll n)
{
ll sized=n;
if(sized==1)
{
return;
}
ll *arr1,*arr2,j=0;
arr1=arr2=NULL;
ll sizedh=sized/2;
arr1=new ll[sizedh];
arr2=new ll[sized-sizedh];
for(ll i=0;i<sizedh;i++)
{
arr1[i]=arr[i];
j++;
}
for(ll i=0;i<sized-sizedh;i++)
{
arr2[i]=arr[j];
j++;
}
mergencount(arr1,sizedh);
mergencount(arr2,sized-sizedh);
stitchncount(arr,arr1,arr2,sizedh,sized-sizedh);
}