Last active
May 13, 2019 15:06
-
-
Save antonxo/dcfa4e6a574a2ee75dbf3496cfb7b1db to your computer and use it in GitHub Desktop.
[C] Sort a singly linked list using Mergesort with a custom callback function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t_lst *merge(t_lst *left, t_lst *right, int (*fp) (t_lst *l, t_lst *r)) | |
{ | |
t_lst *head; | |
head = NULL; | |
if (left == NULL) | |
return (right); | |
if (right == NULL) | |
return (left); | |
if (fp(left, right)) //callback sort function | |
{ | |
head = left; | |
head->next = merge(left->next, right, fp); | |
} | |
else | |
{ | |
head = right; | |
head->next = merge(left, right->next, fp); | |
} | |
return (head); | |
} | |
static t_lst *merge_sort(t_lst *head, int (*fp) (t_lst *l, t_lst *r)) | |
{ | |
t_lst *left; | |
t_lst *right; | |
t_lst *slow; | |
t_lst *fast; | |
if (head == NULL || head->next == NULL) | |
return (head); | |
slow = head; | |
fast = head->next; | |
while (fast && fast->next) //find the middle of the list | |
{ | |
slow = slow->next; | |
fast = fast->next->next; | |
} | |
left = head; //pointer to the left side | |
right = slow->next; //pointer to the right side | |
slow->next = NULL; //set a break in the middle | |
left = merge_sort(left, fp); | |
right = merge_sort(right, fp); | |
return (merge(left, right, fp)); | |
} | |
//example: list_head = merge_sort(list_head); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment