Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Zortech C++ Language Reference - bsearch http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
   bsearch
   Usage
   #include <stdlib.h>
   void  *bsearch(const  void *key,const void *base, size_t  num,  size_t
          width,int (*cmp)(const void *elem1,const void *elem2));

   Description
   bsearch  performs a binary search of a sorted array of  num  elements,
   which  is  pointed to by base, for an element which matches  key.  The
   contents of the array must have been previously sorted into  ascending
   order.  Each item of the array is width bytes. The typedef  size_t  is
   the unsigned integer data type that results from the use of the sizeof
   operator. The function used in the search is *cmp.. This function must
   be supplied by the programmer. The cmp function takes two arguments as
   pointers  to the element in the array. The *cmp function  must  return
   one of the following values:

   <0 elem1 is less than elem2
   0  elem1 and elem2 match
   >0 elem1 is greater then elem2

   Note  that the standard library function strcmp is a suitable  compare
   function (cmp) for C style strings.

   Example
   #include <stdio.h>
   #include <stdlib.h>
   #define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
   int array[] = {1254,3427,1111,3901,6677,0101};

   int intcmp(int *p1, int *p2)
   {
   return(*p1 - *p2);
   }

   main()
   {
   int *pointer;
   int key = 3901;
        pointer = (int *) bsearch(&key,
        array,SIZE(array), sizeof(int),intcmp);
        if(pointer)
             printf("[%d] is in array\n",key);
        else
             printf("[%d] is not in array\n",key);
   }

   Return Value
   Returns a pointer to the matching element, or NULL if not found.


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