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:
2026-10-14 14:01:14 +02:00
parent 9966c6feca
commit f6d43c1292
+7 -12
View File
@@ -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 */ /* 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) if (a->occurrences != b->occurrences)
return a->occurrences < b->occurrences; return b->occurrences - a->occurrences;
return comparer(a->mot, b->mot) > 0; return comparer(a->mot, b->mot);
} }
void trier_entrees(Entree *table, int n) void trier_entrees(Entree *table, int n)
{ {
for (int i = 0; i < n - 1; i++) { qsort(table, n, sizeof(Entree), comparer_entrees);
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;
}
}
}
} }
/* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */