Use bsearch function to do binary search
Syntax
C bsearch function has the following syntax.
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *));
Header
C bsearch function is from header file stdlib.h.
Description
C bsearch function performs a binary search on the sorted array *buf
and
returns a pointer to the first member that matches *key
.
If the array does not contain the key, a null pointer is returned.
Parameter
- The
array
must be sorted in ascending order. - The number of elements in the array is specified by
num
, - The size (in bytes) of each element is described by
size
.
The function pointed to by compare is used to compare an element of the array with the key. The form of the compare function must be as follows:
int func_name(const void *arg1, const void *arg2);
Return
C bsearch function returns values as described in the following table:
Comparison | Value Returned |
---|---|
arg1 < arg2 | < 0 |
arg1 == arg2 | 0 |
arg1 > arg2 | > 0 |
Example
Use C bsearch function to do binary search.
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
/*from w w w .j a v a 2s . co m*/
char *alpha = "abcdefghijklmnopqrstuvwxyz";
int comp(const void *ch, const void *s);
int main(void)
{
char ch;
char *p;
printf("Enter a character: ");
ch = getchar();
ch = tolower(ch);
p = (char *) bsearch(&ch, alpha, 26, 1, comp);
if(p) printf(" %c is in alphabet\n", *p);
else printf("is not in alphabet\n");
return 0;
}
/* Compare two characters. */
int comp(const void *ch, const void *s)
{
return *(char *)ch - *(char *)s;
}