forked from menault/2026_TD3_DEV51_Qualite_Algo
Optimiser F1 avec un tri fusion en O(n log n)
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define NB_TRANSACTIONS 30000
|
||||
#define NB_CLIENTS 2000
|
||||
@@ -71,18 +72,45 @@ Transaction *generer_transactions(int n)
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* F1 : trie les transactions par montant croissant, puis par id */
|
||||
static int comparer_transactions(const Transaction *a, const Transaction *b)
|
||||
{
|
||||
if (a->montant != b->montant)
|
||||
return (a->montant > b->montant) - (a->montant < b->montant);
|
||||
return (a->id > b->id) - (a->id < b->id);
|
||||
}
|
||||
|
||||
static void trier_intervalle(Transaction *t, Transaction *tampon, int debut, int fin)
|
||||
{
|
||||
if (fin - debut < 2)
|
||||
return;
|
||||
|
||||
int milieu = debut + (fin - debut) / 2;
|
||||
trier_intervalle(t, tampon, debut, milieu);
|
||||
trier_intervalle(t, tampon, milieu, fin);
|
||||
|
||||
int gauche = debut;
|
||||
int droite = milieu;
|
||||
for (int i = debut; i < fin; i++) {
|
||||
if (gauche < milieu &&
|
||||
(droite == fin || comparer_transactions(&t[gauche], &t[droite]) <= 0))
|
||||
tampon[i] = t[gauche++];
|
||||
else
|
||||
tampon[i] = t[droite++];
|
||||
}
|
||||
memcpy(t + debut, tampon + debut, (size_t)(fin - debut) * sizeof(*t));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (n < 2)
|
||||
return;
|
||||
Transaction *tampon = malloc((size_t)n * sizeof(*tampon));
|
||||
if (tampon == NULL) {
|
||||
perror("Allocation du tampon de tri");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
trier_intervalle(t, tampon, 0, n);
|
||||
free(tampon);
|
||||
}
|
||||
|
||||
/* F2 : nombre de clients ayant au moins une transaction */
|
||||
|
||||
Reference in New Issue
Block a user