bsearch.c
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003
00004 #define TAB_SIZE 100
00005 struct cell {int key, data; } tab[TAB_SIZE];
00006
00007 int compar(const void * a, const void * b) {
00008 int c = ((struct cell *) a)->key;
00009 int d = ((struct cell *) b)->key;
00010 return (c < d) ? -1 : (c > d) ? 1 : 0;
00011 }
00012
00013 int find(int key) {
00014 struct cell key_elem = { key };
00015 struct cell * res =
00016 (struct cell *) bsearch( (void *) &key_elem, (void *) tab, TAB_SIZE,
00017 sizeof(struct cell), compar);
00018 return (res == NULL) ? 0 : res->data;
00019 }
00020
00021 int main()
00022 {
00023 int i, key=14;
00024 for (i=0; i<TAB_SIZE; i++) {
00025 tab[i].key = i;
00026 tab[i].data = TAB_SIZE - i;
00027 }
00028 printf("recherche de %d dans tab : %d\n",key,find(key));
00029 return 0;
00030 }
00031