How to Use bsearch with an Array in C?
Last Updated :
15 Feb, 2024
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
#include <stdio.h>
#include <stdlib.h>
int compare_ints( const void * a, const void * b)
{
return *( int *)a - *( int *)b;
}
int main()
{
int array[] = { 2, 5, 7, 11, 15 };
int num_elements = sizeof (array) / sizeof (array[0]);
int key = 15;
void * found_element
= bsearch (&key, array, num_elements, sizeof ( int ),
compare_ints);
if (found_element != NULL) {
printf ( "Value %d found!\n" , *( int *)found_element);
}
else {
printf ( "Value not found.\n" );
}
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...