Emmanuel Delahaye C is a sharp tool | finch911 a écrit :
ok j'ai trouver, fallait mettre la ligne 40 deux ligne plus tard...pour que le j-- fasse effet dessus...
|
Une version plus 'professionelle'...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N(a) (sizeof(a)/sizeof*(a))
typedef struct
{
char sis[11];
int indice;
}
org;
char *str_dup (char const *s)
{
char *s_dup = NULL;
if (s != NULL)
{
size_t const size = strlen (s) + 1;
s_dup = malloc (size);
if (s_dup != NULL)
{
memcpy (s_dup, s, size);
}
}
return s_dup;
}
void trierindex (org * pindex, size_t n)
{
size_t i = 1;
while (i < n)
{
char *tmp = str_dup (pindex[i].sis);
if (tmp != NULL)
{
int j = i - 1;
while (j >= 0 && strcmp (tmp, pindex[j].sis) < 0)
{
strcpy (pindex[j + 1].sis, pindex[j].sis);
j--;
}
strcpy (pindex[j + 1].sis, tmp);
free (tmp), tmp = NULL;
}
i++;
}
}
int main (void)
{
org tabo[] =
{
{"BRABN", 2,},
{"OPLO", 4,},
{"PRO", 5,},
{"GUSTAVE", 6,},
{"ALAIN", 7,},
{"XUPONT", 0,},
{"KAPOUL", 9,},
{"JAVERT", 3,},
{"GREG", 2,},
{"JOHN", 3},
};
trierindex (tabo, N (tabo));
{
size_t i;
for (i = 0; i < N (tabo); i++)
{
printf ("%s\n", tabo[i].sis);
}
}
return 0;
} |
Mais attention, les noms ont été déplacés (triés), mais pas les nombres. C'est voulu ?
Sinon, pourquoi ne pas utiliser qsort() ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N(a) (sizeof(a)/sizeof*(a))
typedef struct
{
char sis[11];
int indice;
}
org;
int compare (void const *a, void const *b)
{
org const *pa = a;
org const *pb = b;
return strcmp (pa->sis, pb->sis);
}
int main (void)
{
org tabo[] =
{
{"BRABN", 2,},
{"OPLO", 4,},
{"PRO", 5,},
{"GUSTAVE", 6,},
{"ALAIN", 7,},
{"XUPONT", 0,},
{"KAPOUL", 9,},
{"JAVERT", 3,},
{"GREG", 2,},
{"JOHN", 3},
};
qsort (tabo, N (tabo), sizeof *tabo, compare);
{
size_t i;
for (i = 0; i < N (tabo); i++)
{
printf ("%s (%d)\n", tabo[i].sis, tabo[i].indice);
}
}
return 0;
}
|
Message édité par Emmanuel Delahaye le 04-04-2005 à 14:43:08 ---------------
Des infos sur la programmation et le langage C: http://www.bien-programmer.fr Pas de Wi-Fi à la maison : http://www.cpl-france.org/
|