#include <stdio.h> #include <stdlib.h> typedef struct { unsigned long id; char *nom; char *pays; } client ; int id_cmp(const void *s1, const void *s2); //prototype de comparateur int main( ) { client list_client[ ] = { {3, "sakoba", "France"}, {5, "Bernard", "Belgique"}, {4, "Nicolas", "US"}, {2, "Alex", "Espagne"}, {1, "Bill", "Angleterre"} }; client requete; client *estTrouve = NULL; // résultat de la recherche int nbrClient = sizeof( list_client ) / sizeof ( client ); printf( "Tapez le nombre des clients: "); scanf( "%lu", &requete.id ); printf( "nListe des Clients:nn" "%16s %16s %16s %16sn", "Index", "ID", "nom", "Pays" ); for ( int i = 0; i < nbrClient ; i++ ) printf( "%16d %16u %16s %16sn", i, list_client[i].id, list_client[i].nom, list_client[i].pays ); qsort( list_client, nbrClient, sizeof( client ), id_cmp ); printf( "nListe triée des Clients:nn" "%16s %16s %16s %16sn", "Index", "ID", "nom", "Pays" ); for ( i = 0; i < nbrClient ; i++ ) printf( "%16d %16u %16s %16sn", i, list_client[i].id, list_client[i].nom, list_client[i].pays ); estTrouve = (client *) bsearch( &requete, list_client, nbrClient, sizeof( client ), id_cmp ); if ( estTrouve == NULL ) printf( "Aucun client trouvé avec cet ID %lu.n", requete.id ); else printf( "Voici le client qui a ID %lu : %s. %3sn", requete.id, estTrouve->nom, estTrouve->pays ); return 0; } int id_cmp(const void *s1, const void *s2) { client *p1 = (client *)s1; client *p2 = (client *)s2; if ( p1->id < p2->id ) return -1; else if ( p1->id == p2->id ) return 0; else return 1; } /* Tapez le nombre des clients: 4 Liste des Clients: Index ID nom Pays 0 3 sakoba France 1 5 Bernard Belgique 2 4 Nicolas US 3 2 Alex Espagne 4 1 Bill Angleterre Liste triÚe des Clients: Index ID nom Pays 0 1 Bill Angleterre 1 2 Alex Espagne 2 3 sakoba France 3 4 Nicolas US 4 5 Bernard Belgique Voici le client qui a ID 4 : Nicolas. US */ |
Home »
Stdio.h » Exemple de recherche d’un élément avec la fonction de recherche binaire ‘bsearch()’
0
Exemple de recherche d’un élément avec la fonction de recherche binaire ‘bsearch()’
Tags: char, const, fonction, ID, int, list, long, nombre, printf, qsort, recherche, struct, tri, unsigned
c sniper
No comments yet.