1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| // on aura ici un tableau de deux valeurs de type chaîne de caractères
typedef struct my_struct
{
char *nom;
char *prenom;
} my_struct;
// le tableau à trier
my_struct tab[] =
{
{
"blanc", "michel"
},
{
"simon", "michel"
},
{
"blanc", "gerard"
}
};
// la fonction de tri
int my_comp(void *arg1, void *arg2)
{
// on caste d'abord les arguments de la fonction dans le bon type
my_struct *premier = (my_struct *) arg1;
my_struct *second = (my_struct *) arg2;
// je compare d'abord les noms
int ret = strcmp(premier->nom, second->nom);
// si ce sont les mêmes, je compare les prénoms
if (ret == 0)
ret = strcmp(premier->prenom, second->prenom);
// je retourne le resultat de la comparaison
return ret;
}
void affiche(my_struct *tab, size_t nbElem)
{
size_t n;
for(n = 0; n < nbElem; n++)
printf("%s %s\n", tab[n].nom, tab[n].prenom);
puts("");
}
// dans le prog, j'affiche le tableau avant et après le tri
int main(void)
{
affiche(tab, sizeof tab / sizeof *tab);
// la fonction de tri a besoin de 4 arguments
// le nom du tableau (logique)
// sa taille en nombre d'éléments
// la taille de chaque éléments du tableau
// le nom de la fonction de tri
qsort(tab, sizeof tab / sizeof *tab, sizeof *tab, my_comp);
affiche(tab, sizeof tab / sizeof *tab);
return 0;
} |
Partager