I have written a Merge Sort program in c but getting a segmentation fault. After trying to debug my code i got to know the particular line in which i am getting the error but i wanted to know what is the reason??
Here is my code:
void Mergesort(struct record r[],int n)
{
int k;
if(n>1)
{
int i,j;
struct record r1[n/2];
struct record r2[n/2];
for(i=0,j=n/2;i<n/2,j<n;i++,j++)
{
r1[i]=r[i];
r2[i]=r[j]; // this is the line where i am getting the error.
}
Mergesort(r1,n/2);
Mergesort(r2,n/2);
r=Merge(r1,r2,r,n);
}
}
struct record * Merge(struct record r1[],struct record r2[],struct record r[],int n)
{
int i=0,j=0,k=0;
while(i<n/2 && j<n/2)
{
if (strcmp(r1[i].a,r2[j].a)<=0)
{
r[k]=r1[i];
i=i+1;
}
else
{
r[k]=r2[j];
j=j+1;
}
k=k+1;
}
if(i==n/2)
{
for(j;j<n/2,k<n;j++,k++)
{
r[k]=r2[j];
}
}
else
{
for(i;i<n/2,k<n;i++,k++)
{
r[k]=r1[i];
}
}
return r;
}
One more thing : I am getting segmentation fault only when the no. of entries which i want to sort are not a power of 2. The code is running properly for entries such as 2,4,8,16.