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;
}
/* 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)
{
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (doit_echanger(&table[j], &table[j + 1])) {
Entree tmp = table[j];
table[j] = table[j + 1];
table[j + 1] = tmp;
}
}
if (n < 2)
return;
Entree *tampon = malloc((size_t)n * sizeof(*tampon));
if (tampon == NULL) {
perror("malloc tri");
exit(EXIT_FAILURE);
}
fusionner_entrees(table, tampon, 0, n);
free(tampon);
}
/* ------------------------------------------------------------------------ */