i wrote the following code for counting the number of inversions in c++ using divide and conquer but it's not working can someone tell me what is going wrong here? Can someone explain what is wrong with my code and not post a link to any other related question as i have gone through them and cant figure out what is wrong with mine
#include <iostream>
#include <string>
using namespace std;
int merge_count_inverse(int left[],int right[]) /*counting number of inversion using merge sort*/
{
int i=0;
int c=0;
int r=0;
int j=0;
int len_arr=0;
int len_left=(sizeof(left)/sizeof(*left));
int len_right=(sizeof(right)/sizeof(*right));
len_arr=(len_left+len_right);
int arr[len_arr];
while((i<len_left)||(j<len_right))
{
if (left[i]<right[j])
{
arr[r]=left[i];
r++;
i++;
}
if (left[i]>right[j])
{
arr[r]=right[j];
r++;
j++;
c=c+len_left-i;
}
}
return (c);
}
int sort_count(int arr[])
{
int cou=0;
int l=0;
int r=0;
int m=0;
int len_arr=(sizeof(arr)/sizeof(*arr));
int middle=0;
middle=len_arr/2;
int left[middle];
int right[middle];
if (len_arr <2)
{
return(0);
}
else
{
for (int i=0;i<=(middle-1);i++)
{
left[i]=arr[i];
right[i]=arr[middle+i];
}
l=l+sort_count(left);
r=r+sort_count(right);
m=m+merge_count_inverse(left,right);
cou=cou+l+r+m;
return(cou);
}
}
int main()
{
int arr[8]={2,5,1,3,8,7,6,9};
int len_arr=(sizeof(arr)/sizeof(*arr));
int co=0;
co+=sort_count(arr);
cout<<co;
}
I did not look through all your code but it will be enough to point out that function sort_count
is invalid. Its parameter is adjusted to int *
So the calculation of len_arr
has no sense
int sort_count(int arr[])
{
// ...
int len_arr=(sizeof(arr)/sizeof(*arr));
In fact the shown statement is equivalent to
int len_arr=(sizeof( int * )/sizeof( int ));
You should either define the function as a template function that has a parameter of type of a reference to an array or as a non-template function having two parameters. The second parameter will specify the size of the array.
The same is valid for function merge_count_inverse
int merge_count_inverse(int left[],int right[]) /*counting number of inversion using merge sort*/
{
// ...
int len_left=(sizeof(left)/sizeof(*left));
int len_right=(sizeof(right)/sizeof(*right));
The calculations of len_left
and len_right
have no sense because left
and right
are not arrays. They are pointers int *