Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Borland C++ 2.x ( with Turbo C ) - <b>bsearch() perform binary search</b> http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
 bsearch()               Perform Binary Search

 #include   <stdlib.h>

 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)(const void *e1,const void *e2);   Pointer to compare function

    bsearch() searches a table of information arranged in ascending
    order.  The table is an array of 'num' elements, each of size 'width'
    bytes. 'base' is a pointer to the base of the array being searched.
    'key' is the item being sought.  'compare' points to a user-supplied
    routine that compares two array elements and returns a value based on
    the comparison.

    bsearch() calls the compare() function one or more times during the
    search, each time passing pointers to two 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'.  Zero is returned if
                    'key' is not found.

         Notes:     The elements of the array pointed to by 'base' should
                    be in ascending order before the search begins.

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

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

           #include <stdlib.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 != 0)
                  printf("%d found 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