I am trying to sort linked list using merge sort but every time i get a segmentation fault i have been trying very hard from 2 days and ran debugger many times please some one help . I followed approach of dividing the linked list into 2 parts and recursively calling merge sort .
void merge_sort(Node**head){
if((*head)->next == NULL){
return ;
}
Node *a , *b ;
FrontBackSplit( *head, &a, &b);
merge_sort(&a);
merge_sort(&b);
*head = merge(a,b);
}
Node *merge(Node *a , Node*b){
Node *result = NULL ;
if(a == NULL){
return b;
}
else if(b == NULL){
return a;
}
if(a->data <= b->data){
result = a;
result->next = merge(a ->next,b) ;
}
else {
result = b;
result->next = merge(a , b->next) ;
}
return result ;
}
void FrontBackSplit(Node* source,
Node** frontRef, Node** backRef)
{
Node* fast;
Node* slow;
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list, so split it in two
at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}