VMS Help  —  CRTL  bsearch  Example
 #include <stdio.h>
 #include <stdlib.h>

 #define SSIZE 30

 extern int compare();  /* prototype for comparison function */

 int array[SSIZE] = {30, 1, 29, 2, 28, 3, 27, 4, 26, 5,
                     24, 6, 23, 7, 22, 8, 21, 9, 20, 10,
                     19, 11, 18, 12, 17, 13, 16, 14, 15, 25};

  /*  This program takes an unsorted array, sorts it using qsort, */
  /*  and then calls bsearch for each element in the array,       */
  /*  making sure that bsearch returns the correct element.       */

 main()
 {
     int i;
     int failure = FALSE;
     int *rkey;

     qsort(array, SSIZE, sizeof (array[0]), &compare);

     /* search for each element */
     for (i = 0; i < SSIZE - 1; i++) {
         /* search array element i */
         rkey = bsearch((array + i), array, SSIZE,
                         sizeof(array[0]), &compare);
         /* check for successful search */
         if (&array[i] != rkey) {
             printf("Not in array, array element %d\n", i);
             failure = TRUE;
             break;
         }
     }
     if (!failure)
         printf("All elements successfully found!\n");
 }

  /*  Simple comparison routine.  */
  /*                              */
  /*  Returns:  = 0 if a == b     */
  /*            < 0 if a < b      */
  /*            > 0 if a > b      */

 int compare(int *a, int *b)
 {
     return (*a - *b);
 }

      This example program outputs the following:

        All elements successfully found!
Close Help