TP 9 exo2: Implement a merge sort function for the linked list.
[TD_C.git] / TP_9 / exo2 / clist.c
index afdb00f6c12e84617d2d360dc331c8849dee94a5..ae7db6fcb6d5740ac59921ca684e960d88971b75 100644 (file)
@@ -1,5 +1,6 @@
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
 #include <stdbool.h>
 
 #include "clist.h"
@@ -118,6 +119,47 @@ link_t* list_sort(link_t* head) {
     return head_first;
 }
 
+static link_t* _list_merge_sort(link_t* head1, link_t* head2) {
+    link_t* head_result = NULL;
+
+    if (head1 == NULL) {
+        return head2;
+    }
+    if (head2 == NULL) {
+        return head1;
+    }
+    if (head1->value < head2->value) {
+        head_result = head1;
+       head_result->next = _list_merge_sort(head1->next, head2);
+    } else {
+        head_result = head2;
+       head_result->next = _list_merge_sort(head1, head2->next);
+    }
+    return head_result;
+}
+
+link_t* list_merge_sort(link_t* head) {
+    link_t* head1;
+    link_t* head2;
+
+    if (head == NULL || head->next == NULL) {
+        return head;
+    }
+
+    head1 = head;
+    head2 = head->next;
+    while (head2 != NULL && head2->next != NULL) {
+        head = head->next;
+       head2 = head->next->next;
+    }
+    head2 = head->next;
+    head->next = NULL;
+
+    head1 = list_merge_sort(head1);
+    head2 = list_merge_sort(head2);
+    return _list_merge_sort(head1, head2);
+}
+
 unsigned list_count(link_t* head) {
     unsigned count = 0;