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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person
{
char * FirstName;
char * FamilyName;
int Age;
};
int compareAge( void const * lhs, void const * rhs )
{
struct Person * left = ((struct Person *) lhs);
struct Person * right = ((struct Person *) rhs);
if(strcmp(left->FirstName , right->FirstName ))
{
if( left->Age < right->Age ) return -1;
if( left->Age > right->Age ) return 1;
}
return 0;
}
int main ( void )
{
struct Person figures[] = { { "Max", "Mustermann", 40 }
, { "Erika", "Mustermann", 38 }
, { "Jane", "Doe", 32 }
, { "Anna", "Gabler", 38 }
, { "John", "Doe", 34 }
, { "Anna", "Mustermann", 51 }
, { "Ann", "MissX", 52 }
, { "Anne", "Mustermann", 53 }
, { "Anna", "Mustermann", 54 }
, { "Anna", "Mustermann", 55 }
, NULL };
int const elements = 10;
int const ageKey = 52;
char* const nameKey = "Anni";
int i = 0;
qsort( figures, elements, sizeof( struct Person ), compareAge );
struct Person key;
key.Age = ageKey;
key.FirstName = nameKey;
struct Person* result = (Person*) bsearch( &key, figures, elements, sizeof( struct Person ), compareAge );
if( result )
printf( "gefunden: %s, %s (%d)\n", result->FamilyName, result->FirstName, result->Age );
else
printf( "nichts gefunden\n" );
return EXIT_SUCCESS;
}
|