forked from menault/2026_TD1_DEV51_Qualite_Algo
Remplacer le tri à bulles par qsort
Le tri à bulles faisait n(n-1)/2 = 17,2 millions de comparaisons pour 5 866 mots. qsort trie en O(n log n) avec une fonction de comparaison équivalente (occurrences décroissantes, puis ordre alphabétique). Les mots étant tous distincts, l'ordre est total : le résultat est le même malgré un tri non stable. Temps : 0,53 s → 0,20 s. Empreinte inchangée (1d53de903efd2b7c). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+7
-12
@@ -294,24 +294,19 @@ void compter_mots_ligne(Entree *table, int *nb_entrees, const char *ligne,
|
||||
/* Tri : par nombre d'occurrences décroissant, puis ordre alphabétique */
|
||||
/* ------------------------------------------------------------------------ */
|
||||
|
||||
int doit_echanger(const Entree *a, const Entree *b)
|
||||
/* Les mots de la table sont tous distincts : cet ordre est total, donc qsort
|
||||
* (pourtant non stable) donne exactement le même résultat que le tri à bulles. */
|
||||
int comparer_entrees(const void *pa, const void *pb)
|
||||
{
|
||||
const Entree *a = pa, *b = pb;
|
||||
if (a->occurrences != b->occurrences)
|
||||
return a->occurrences < b->occurrences;
|
||||
return comparer(a->mot, b->mot) > 0;
|
||||
return b->occurrences - a->occurrences;
|
||||
return comparer(a->mot, b->mot);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
qsort(table, n, sizeof(Entree), comparer_entrees);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------ */
|
||||
|
||||
Reference in New Issue
Block a user