Open In App

How to Use bsearch with an Array in C?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The bsearch() is a library function in C that is used to perform binary search on a given sorted array. In this article, we will learn how to use search on an array in C.

Example

Input: 
arr[]= { 2, 5, 7, 11, 15 };
Key=15

Output:
Value 15 found!

bsearch() with an Array in C

To use bsearch() on a given array we need to pass the sorted array, key (the element we want to search), size of each element in the array, the total number of elements in an array, and a comparator function which will help the bsearch to find the matching value. The comparator function should return the result as

  • If the first argument is less than the second, the result is a negative integer.
  • If the first argument is greater than the second, the result is a positive integer.
  • If the arguments are equal, the result is zero.

the bsearch will return a pointer to the element if it is found otherwise it will return NULL.

Syntax of bsearch()

bsearch(key, ptr, num, size, comp);

C++ Program to Use bsearch with an Array

The below example demonstrates the use of bsearch() with an array.

C




// Program to search for an element in an array using binary
// search
  
#include <stdio.h>
#include <stdlib.h>
  
// Comparator function for integer values
int compare_ints(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}
  
int main()
{
  
    // initializing an array
    int array[] = { 2, 5, 7, 11, 15 };
    int num_elements = sizeof(array) / sizeof(array[0]);
    // key to be searched
    int key = 15;
  
    // Perform binary search
    void* found_element
        = bsearch(&key, array, num_elements, sizeof(int),
                  compare_ints);
  
    // Check if the element is found
    if (found_element != NULL) {
        printf("Value %d found!\n", *(int*)found_element);
    }
    else {
        printf("Value not found.\n");
    }
  
    return 0;
}


Output

Value 15 found!


Time Complexity: O(log N)
Auxiliary Space: O(1)

Note: The array must be sorted before using bsearch because the behavior of bsearch is undefined in case the array is not sorted.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads