Advertisement
Guest User

Untitled

a guest
Nov 14th, 2009
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. static struct node *merge(struct linked_list *list,
  2.     int (*cmp)(const void *, const void *),
  3.     struct node *left, struct node *right, size_t right_count)
  4. {
  5.     struct node *head;
  6.     if(cmp(left->data, right->data) <= 0)
  7.     {
  8.         head = left;
  9.         left = left->next;
  10.     }
  11.     else
  12.     {
  13.         head = right;
  14.         struct node *node = right;
  15.         right = right->next;
  16.         remove_node(node, list);
  17.         insert_before(node, list, left);
  18.         --right_count;
  19.     }
  20.  
  21.     while(left != right && right_count)
  22.     {
  23.         if(cmp(left->data, right->data) <= 0)
  24.             left = left->next;
  25.         else
  26.         {
  27.             struct node *node = right;
  28.             right = right->next;
  29.             remove_node(node, list);
  30.             insert_before(node, list, left);
  31.             --right_count;
  32.         }
  33.     }
  34.  
  35.     return head;
  36. }
  37.  
  38. static struct node *mergesort(struct linked_list *list,
  39.     int (*cmp)(const void *, const void *), struct node *head, size_t size)
  40. {
  41.     if(size < 2) return head;
  42.     size_t left_count = size / 2;
  43.     size_t right_count = size - left_count;
  44.  
  45.     struct node *tail = head;
  46.     size_t count = left_count;
  47.     while(count--) tail = tail->next;
  48.  
  49.     return merge(list, cmp,
  50.         mergesort(list, cmp, head, left_count),
  51.         mergesort(list, cmp, tail, right_count),
  52.         right_count);
  53. }
  54.  
  55. static void sort(struct linked_list *list,
  56.     int (*cmp)(const void *, const void *))
  57. {
  58.     mergesort(list, cmp, list->first, list->size);
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement