diff options
author | Tobias Klauser <tklauser@distanz.ch> | 2008-01-27 11:37:44 +0100 |
---|---|---|
committer | Tobias Klauser <tklauser@xenon.tklauser.home> | 2008-01-27 11:37:44 +0100 |
commit | 7e0f021a9aec35fd8e6725e87e3313b101d26f5e (patch) | |
tree | b1cacc4b24393f517aeb4610e9e1021f954307a8 /reference/C/EXAMPLES/bsearch.c |
Initial import (2.0.2-6)2.0.2-6
Diffstat (limited to 'reference/C/EXAMPLES/bsearch.c')
-rw-r--r-- | reference/C/EXAMPLES/bsearch.c | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/reference/C/EXAMPLES/bsearch.c b/reference/C/EXAMPLES/bsearch.c new file mode 100644 index 0000000..618f114 --- /dev/null +++ b/reference/C/EXAMPLES/bsearch.c @@ -0,0 +1,44 @@ +/************************************************************************ + * + * Purpose: To demonstrate the 'bsearch' function. + * + * Author: M.J. Leslie + * + * Date: 04-Jun-95 + * + ************************************************************************/ + +#include <stdlib.h> + +#define NUM 11 + +static int func (void *, void *); + +/************************************************************************/ + +main() +{ + /* List of numbers. */ + int numbers[NUM]={3,4,7,9,11,13,15,17,19,21,23}; + int key=22; /* number to find. */ + int * result; /* Result of 'bsearch' */ + + /* Search for 'key' in 'numbers'*/ + + result = bsearch (&key, numbers, NUM, sizeof(numbers[0]), (void *)func); + + printf("%d ", key); + (result) ? puts("found") : puts("not found"); +} + +/************************************************************************/ + +static int func (void *a, void *b) +{ + printf("%d %d \n", *(int *)a, *(int *)b); /* Diagnistics. */ + + /* Compare the two numbers */ + if (*(int *)a == *(int *)b) return(0); + if (*(int *)a < *(int *)b) return(-1); + return (1); +} |