bsearch : library function

The stdlib C Library function bsearch searches the given key in an sorted array pointed by base and returns a void pointer in the table that matches the search key.

To perform the binary search, the function uses a comparison function(compare) to compare any element of array with key. The elements of the array must be in ascending sorted order for binary search to work properly.

Here is the return value of comparison function int compare(const void *x, const void *y).
  • If *x < *y, compare function should return an integer < 0.
  • If *x == *y, compare function should return 0.
  • If *x > *y, compare function should return an integer > 0.

Function prototype of bsearch

void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compare)(const void *, const void *));
  • key : This is the pointer to the element to be searched which serves as key of binary search, type-casted as a void*.
  • base : This is a pointer to the first element of the sorted array where the search to be performed, type-casted to a void*.
  • num : This is the number of elements in the sorted array pointed by base.
  • size : This is size in bytes of each element in the sorted array.
  • compare : This is a pointer to a function that compares two elements.

Return value of bsearch

This function returns a pointer to an element in the array that matches the search key otherwise a NULL pointer is returned If key is not found in array. In case of multiple occurrence of key in array this may point to any one of them(not necessarily the first one).

C program using bsearch function

The following program shows the use of bsearch function to search an integer in a sorted integer array.

bsearch : <stdlib.h> library function

#include <stdio.h>
#include <stdlib.h>
 
int compare(const void *x, const void *y){
   return (*(int*)x - *(int*)y);
}
 
int main(){
    int array[50], counter, n;
    int toSearch, *ptr;
     
    printf("Enter number of elements\n");
    scanf("%d", &n);
 
    printf("Enter %d numbers in increasing order\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
 
    printf("Enter element to search\n");
    scanf("%d", &toSearch);
    /* Binary Search on sorted array*/
    ptr = (int*)bsearch(&toSearch, array, n, sizeof (int), compare);
     
    if(ptr != NULL) {
        printf("%d found at index %d\n", toSearch, ptr-array);
    } else {
        printf("%d not be found\n", toSearch);
    }
     
    return 0;
}

Output

Enter number of elements
5
Enter %d numbers in increasing order
1 3 4 9 10
Enter element to search
9
9 found at index 3