/************************************************************************ * * * Copyright Digital Equipment Corporation 1998. All rights reserved. * * * * Restricted Rights: Use, duplication, or disclosure by the U.S. * * Government is subject to restrictions as set forth in subparagraph * * (c) (1) (ii) of DFARS 252.227-7013, or in FAR 52.227-19, or in FAR * * 52.227-14 Alt. III, as applicable. * * * * This software is proprietary to and embodies the confidential * * technology of Digital Equipment Corporation. Possession, use, or * * copying of this software and media is authorized only pursuant to a * * valid written license from Digital or an authorized sublicensor. * * * ************************************************************************/ /* bserch_example.c */ #include #include #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); }