I tried implementing the merge sort code for linked list. It is giving segmentation fault. I checked the midpoint function it is working properly and the insertattail is also working properly i guess the fault is in mergesorted function can you please help me correct that function?
Segmentation fault in mersort
Hey @prerna_gupta31
There are 2 corrections
node * mergesorted(node *& a, node *& b)
{
if(a==NULL)
{
return b;
}
else if(b==NULL)
{
return a;
}
node * result ;
if(a->data<=b->data) //coorecte this
{
result = a;
result->next = mergesorted(a->next,b);
}
else
{
result = b;
result->next = mergesorted(a,b->next);
}
return result;
}
node * mergesort(node * &head)
{
if(head==NULL || head->next==NULL)
{
return head;
}
node * m = midpoint(head);
node * a = head;
node * b = m->next;
m->next=NULL; //added this
a = mergesort(a);
b = mergesort(b);
node * c = mergesorted(a,b);
return c;
}
If this resolves your query then please mark it as resolved
thanks it solved the problem but what is the significance of this m->next=NULL; ?
When we apply mergesort in arrays we work on smaller arrays right
If we don’t apply m->next=NULL then first list will always be equal to bigger list hence giving unwanted results