Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Microsoft C 6.0 - <b>bsearch() performs binary search</b> http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
 bsearch()               Performs Binary Search

 #include   <search.h>
 #include   <stdlib.h>                   For ANSI compatibility

 void       *bsearch(key,base,num,width,compare());
 const void *key;                        Search key
 const void *base;                       Pointer to base of search data
 size_t     num, width;                  Number and width of elements
 int        (*compare)(e1,e2);           Pointer to compare function
 const void *el, *e2;                    Array elements in compare()

    bsearch() is designed to search a table of information, which is a
    sorted array of 'num' elements, each element being of size 'width'
    bytes. 'base' is a pointer to the base of the array being searched.
    'key' is the item searched for.

    'compare' points to a user-supplied routine that compares two array
    elements and returns a value based on the comparison.  During the
    search, bsearch() calls the compare() function one or more times,
    each time passing pointers to two array elements.  Compare() should
    compare the two elements and return one of the following values:

                  <  0       element1 is less than element2
                     0       element1 is identical to element2
                  >  0       element1 is greater than element2

    Returns:    A pointer to the first occurrence of 'key' in the array
                pointed to by 'base'.  NULL is returned if 'key' is not
                found.

      Notes:    The elements of the array pointed to by 'base' should
                already be in ascending order before being searched.

   -------------------------------- Example ---------------------------------

    The following statements search an array for a value and print out an
    appropriate message.

           #include <search.h>
           #include <stdio.h>
           include <string.h>

           int vals[] = {10,20,30,40,50,60,70,80,90,100};
           int num = 10;
           int key = 60;
           int *found;
           int cmp();

           main()
           {
               found = (int *)bsearch(&key,vals,num,sizeof(int),cmp);
               if (found != NULL)
                  printf("%d already in table\n",key);
               else
                   printf("%d not found\n",key);
           }

           int cmp(n1,n2)
           int *n1;
           int *n2;
           {
               return(*n1 - *n2);
           }


See Also: lfind() lsearch() qsort()

Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson