F1 : trier les transactions avec qsort (O(n²) → O(n log n))

Le tri à bulles faisait n(n-1)/2 = 450 millions de comparaisons pour
30 000 transactions. qsort trie en O(n log n) avec une fonction de
comparaison (montant, puis id). Les id étant distincts, l'ordre est
total et le résultat identique malgré un tri non stable.

Temps (-O2) : 3,05 s → 1,17 s. Empreinte inchangée (ff68d260a7a58441).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 10:42:34 +02:00
parent 3a29495281
commit cb7857cd43
+12 -11
View File
@@ -70,19 +70,20 @@ Transaction *generer_transactions(int n)
/* Fonctions à analyser et à optimiser */
/* ------------------------------------------------------------------ */
/* F1 : trie les transactions par montant croissant, puis par id */
/* F1 : trie les transactions par montant croissant, puis par id.
* Les id sont tous distincts : l'ordre est total, donc qsort (non stable)
* donne le même résultat que le tri à bulles d'origine. */
int comparer_transactions(const void *pa, const void *pb)
{
const Transaction *a = pa, *b = pb;
if (a->montant != b->montant)
return (a->montant > b->montant) - (a->montant < b->montant);
return (a->id > b->id) - (a->id < b->id);
}
void trier_par_montant(Transaction *t, int n)
{
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (t[j].montant > t[j + 1].montant ||
(t[j].montant == t[j + 1].montant && t[j].id > t[j + 1].id)) {
Transaction tmp = t[j];
t[j] = t[j + 1];
t[j + 1] = tmp;
}
}
}
qsort(t, n, sizeof(Transaction), comparer_transactions);
}
/* F2 : nombre de clients ayant au moins une transaction */