From: Jérôme Benoit Date: Fri, 3 Mar 2017 17:44:09 +0000 (+0100) Subject: Properly handle memory management for merge sort implementation. X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=4c872c23a605b7144ea5e9fbd835580a6d834735;p=Algorithmic_C.git Properly handle memory management for merge sort implementation. Signed-off-by: Jérôme Benoit --- diff --git a/TP3/tp3.c b/TP3/tp3.c index 8baa7dc..75c3195 100644 --- 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); } }