Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- 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   <search.h>

 char       *bsearch(key,base,num,width,compare);
 char       *key;                        Search key
 char       *base;                       Pointer to base of search data
 unsigned   num, width;                  Number and width of elements
 int        (*compare)();                Pointer to compare function

    bsearch() is designed to search a table of information.  The table is
    a sorted 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 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 == 0)
               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