forked from menault/2026_TD1_DEV51_Qualite_Algo
Remplacer le tri a bulles par un tri fusion
This commit is contained in:
+28
-8
@@ -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);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------ */
|
||||
|
||||
Reference in New Issue
Block a user