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;
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------------ */
|
||||||
|
|||||||
Reference in New Issue
Block a user