Share on Google+Share on Google+

bsearch() function in C

This section demonstrates the use bsearch()function in C Language.

bsearch() function in C Programming Language

This section demonstrates the use bsearch() function in C. This searches function the given key in the array pointed by base. Here we are going to search a particular character from the character array. To perform the search, the bsearch() function compares the elements of the specified array to the key by calling the function comp(). This function must accept two parameters that are pointers to elements, type-casted as void* and compare their values which returns the result of the subtraction of the values pointed by both.

If the values are equal, it will return 0,
If the value pointed by a is greater than the b, it will return 1,
If the value pointed by b is greater than the a, it will return -1.

In the main function, user is allowed to input the character to search and call to bsearch() function with input character as a key. It will search that key in the array of values whether it is there or not.

Here is the code:

#include <stdlib.h>
#include <stdio.h>

char charr[] = { 'a', 'b', 'c', 'd' };
comp(const void *a, const void *b);
int main(void) {
        char ch;
        char *p;
        printf("Enter a character: ");
        ch = getchar();
        ch = tolower(ch);
        p = (char *) bsearch(&ch, charr, 4, 1, comp);
        if (p)
           printf(" %c is in the Array\n", *p);
           printf(" %c is not in the Array\n");
        return 0;
comp(const void *a, const void *b) {
        return *(char *) a - *(char *) b;


Enter a character: h
h is not in the Array

Enter a character: a
a is in the Array


Posted on: December 26, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.