No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Trier des structures...

Introduction

Pour rappel : les structures en C.

Nous travaillons avec une structure de type "individu" composée de deux champs: un matricule, et un nom.
Les différentes occurences structures sont ensuite placées dans un tableau.

Composition de structure en C

#define NMAX 25

typedef struct { unsigned int mat; char nom[20]; } Individu;
Individu tableau[NMAX];

En supposant que les valeurs ont été préalablement affectées aux différents champs, nous pourions provoquer l'affichage des structures de cette manière:

Affichage de structure en C


for ( k=0; k<NMAX; k++ )
printf ("Matricule : %d -> Individu : %s\n", Individu[k].mat, Individu[k].nom);


Contents Haut

Fonctions de tri de structure en C

Nous allons revoir nos fonctions de tri d'entiers, et les adapter à un tri de structures...

Tri de structure

enum { MAT, NOM, NOMMAT }; //critère de comparaison

void tri( Individu t[], int n, int id)
{
int p, temp, k1, k2;
for (k1=0;k1<n;k1++)
{
p=k1;
for (K2=k1+1;k2<n;k2++)
if ( compare(t[k1],t[k2],id) >0 )
{
p=k2;
}
permute(&t[k1], &t[k2]);
}
}

Comparer et permuter des structures

int compare (Individu x, Individu y, int choix)
{
int r;
switch(choix)
{
case MAT : return px->mat-py->mat;
case NOM : return strcmp(px->nom,pyb->nom);
case NOMAT : r=strcmp(px->nom,py->nom); return r!=0 ? r : px->mat-pyb->mat;
default : return px->mat-py->mat;
}
}

void permute (Individu *x, Individu *y)
{
Individu w ;
w=*x;
*x=*y;
*y=w;
}

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 12/03/2003, last modified the 07/04/2023
Source of the printed document:https://www.gaudry.be/en/c-trier-structure.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.