Properly handle memory management for merge sort implementation.
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Fri, 3 Mar 2017 17:44:09 +0000 (18:44 +0100)
committerJérôme Benoit <jerome.benoit@piment-noir.org>
Fri, 3 Mar 2017 17:44:09 +0000 (18:44 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
TP3/tp3.c

index 8baa7dcf890d6d1df499f49d0a5c09c78a1b5042..75c31950ff86a0b98200864c0c36c4cd4413ffb7 100644 (file)
--- a/TP3/tp3.c
+++ b/TP3/tp3.c
@@ -12,40 +12,39 @@ void TriFusion(int T[], int n) {
     int i = 0, j = 0, k = 0;
     int* T1;
     int* T2;
-
-    T1 = malloc(n/2*sizeof(int));
-    T2 = malloc(n/2*sizeof(int));
     
     if (n > 1) {
+        T1 = malloc(n/2*sizeof(int));
+        T2 = malloc(n/2*sizeof(int));
         for (int i = 0; i < n/2; i++) {
             T1[i] = T[i];
             T2[i] = T[i + n/2];
         }
-    TriFusion(T1, n/2);
-    TriFusion(T2, n/2);
-    while (k < n/2 && j < n/2) {
-        if (T1[k] <= T2[j]) {
+        TriFusion(T1, n/2);
+        TriFusion(T2, n/2);
+        while (k < n/2 && j < n/2) {
+            if (T1[k] <= T2[j]) {
+                T[i] = T1[k];
+                i++;
+                k++;
+            } else {
+                T[i] = T2[j];
+                i++;
+                j++;
+            }
+        }
+        while (k < n/2) {
             T[i] = T1[k];
             i++;
             k++;
-        } else {
+        }
+        while (j < n/2) {
             T[i] = T2[j];
             i++;
             j++;
-        }
-    }
-    while (k < n/2) {
-        T[i] = T1[k];
-        i++;
-        k++;
-    }
-    while (j < n/2) {
-        T[i] = T2[j];
-        i++;
-        j++;
-    }
-    free(T1);
-    free(T2);
+        } 
+        free(T1);
+        free(T2);
     } 
 }