C programming stdlib.h function - void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(con

‮igi.www‬ftidea.com

The bsearch function is a standard library function in C that performs a binary search on a sorted array. It takes as input a key to search for, a pointer to the base of the array, the number of items in the array, the size of each item in bytes, and a comparison function that determines the ordering of the elements.

The syntax of the bsearch function is as follows:

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));

Here is how the parameters are used:

  • key: A pointer to the value to search for.
  • base: A pointer to the base of the array to search.
  • nitems: The number of elements in the array.
  • size: The size of each element in bytes.
  • compar: A function that compares two elements of the array.

The bsearch function returns a pointer to the matching element in the array, or NULL if the key is not found.

The comparison function must have the following signature:

int compar(const void *a, const void *b);

The function should return a negative value if a is less than b, a positive value if a is greater than b, and zero if a is equal to b. The comparison function is responsible for interpreting the binary data as the appropriate data type and performing the comparison.

Here is an example that demonstrates how to use the bsearch function to search for an integer in a sorted array:

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

int cmpfunc(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 10;
    int *ptr;

    qsort(arr, n, sizeof(int), cmpfunc);

    ptr = (int*) bsearch(&key, arr, n, sizeof(int), cmpfunc);

    if (ptr != NULL) {
        printf("%d is present at index %d.\n", key, ptr - arr);
    } else {
        printf("%d is not present in the array.\n", key);
    }

    return 0;
}

In this example, the bsearch function is used to search for the value 10 in the arr array, which is sorted in ascending order. The qsort function is first used to sort the array in ascending order. The bsearch function is called with the key 10, a pointer to the beginning of the array, the number of elements in the array, the size of each element, and the cmpfunc comparison function. The function returns a pointer to the element in the array that matches the key, which is then printed to the console using printf.

Note that the bsearch function assumes that the array is sorted in ascending order. If the array is not sorted, the results are undefined. Also, the comparison function must return consistent results, or the behavior of the bsearch function is undefined.