Remplacer le tri a bulles par un tri fusion

This commit is contained in:
2026-10-07 10:37:01 +02:00
parent 5d71287a57
commit dddcfd4fd5
+28 -8
View File
@@ -317,17 +317,37 @@ int doit_echanger(const Entree *a, const Entree *b)
return comparer(a->mot, b->mot) > 0; return comparer(a->mot, b->mot) > 0;
} }
/* Tri fusion : même ordre total, O(n log n), mémoire O(n). */
void fusionner_entrees(Entree *table, Entree *tampon, int debut, int fin)
{
if (fin - debut < 2)
return;
int milieu = debut + (fin - debut) / 2;
fusionner_entrees(table, tampon, debut, milieu);
fusionner_entrees(table, tampon, milieu, fin);
int gauche = debut, droite = milieu;
for (int k = debut; k < fin; k++) {
if (gauche < milieu && (droite == fin ||
!doit_echanger(&table[gauche], &table[droite])))
tampon[k] = table[gauche++];
else
tampon[k] = table[droite++];
}
for (int k = debut; k < fin; k++)
table[k] = tampon[k];
}
void trier_entrees(Entree *table, int n) void trier_entrees(Entree *table, int n)
{ {
for (int i = 0; i < n - 1; i++) { if (n < 2)
for (int j = 0; j < n - 1 - i; j++) { return;
if (doit_echanger(&table[j], &table[j + 1])) { Entree *tampon = malloc((size_t)n * sizeof(*tampon));
Entree tmp = table[j]; if (tampon == NULL) {
table[j] = table[j + 1]; perror("malloc tri");
table[j + 1] = tmp; exit(EXIT_FAILURE);
}
}
} }
fusionner_entrees(table, tampon, 0, n);
free(tampon);
} }
/* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */