forked from menault/2026_TD3_DEV51_Qualite_Algo
opti tri_par_montant
This commit is contained in:
@@ -71,15 +71,48 @@ Transaction *generer_transactions(int n)
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* F1 : trie les transactions par montant croissant, puis par 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;
|
||||
static void fusionner(Transaction *t, int debut, int milieu, int fin) {
|
||||
int n1 = milieu - debut + 1;
|
||||
int n2 = fin - milieu;
|
||||
|
||||
Transaction *gauche = malloc(n1 * sizeof(Transaction));
|
||||
Transaction *droite = malloc(n2 * sizeof(Transaction));
|
||||
|
||||
for (int i = 0; i < n1; i++)
|
||||
gauche[i] = t[debut + i];
|
||||
for (int j = 0; j < n2; j++)
|
||||
droite[j] = t[milieu + 1 + j];
|
||||
|
||||
int i = 0, j = 0, k = debut;
|
||||
|
||||
while (i < n1 && j < n2) {
|
||||
if (gauche[i].montant < droite[j].montant ||
|
||||
(gauche[i].montant == droite[j].montant && gauche[i].id <= droite[j].id)) {
|
||||
t[k++] = gauche[i++];
|
||||
} else {
|
||||
t[k++] = droite[j++];
|
||||
}
|
||||
}
|
||||
|
||||
while (i < n1)
|
||||
t[k++] = gauche[i++];
|
||||
while (j < n2)
|
||||
t[k++] = droite[j++];
|
||||
|
||||
free(gauche);
|
||||
free(droite);
|
||||
}
|
||||
|
||||
void trier_par_montant(Transaction *t, int n) {
|
||||
if (n <= 1) return;
|
||||
|
||||
for (int taille = 1; taille < n; taille *= 2) {
|
||||
for (int debut = 0; debut < n - 1; debut += 2 * taille) {
|
||||
int milieu = debut + taille - 1;
|
||||
int fin = (debut + 2 * taille - 1 < n - 1) ? (debut + 2 * taille - 1) : (n - 1);
|
||||
|
||||
if (milieu < fin) {
|
||||
fusionner(t, debut, milieu, fin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user