Example of bsearch() in C
The below example demonstrates how we can search an element using bsearch() in C.
// C Program to search an element using bsearch() function
// in C
#include <stdio.h>
#include <stdlib.h>
// Comparison function for bsearch()
int compare(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
int main()
{
// Initialize array
int arr[] = { 1, 2, 3, 4, 5 };
// Calculate the number of elements in the array
int n = sizeof(arr) / sizeof(arr[0]);
// Define the key to search for
int key = 3;
// Declare a pointer to hold the result of the search
int* item;
// Sort the array using qsort()
qsort(arr, n, sizeof(int), compare);
// Search for the key in the array using bsearch()
item
= (int*)bsearch(&key, arr, n, sizeof(int), compare);
// If the key is found, print its value and index
// If not found, print a message indicating it was not
// found
if (item != NULL) {
printf("%d Found at index %ld\n", *item,
item - arr);
}
else {
printf("Key = %d is not found\n", key);
}
return 0;
}
Output
3 Found at index 2
Time Complexity: O(log N), where n is the number of elements in the array.
Auxilliary Space: O(1)
bsearch() Function in C
In C programming language, bsearch() function is used to perform a binary search on a sorted array to search for an element. The name bsearch stands for “binary search” which is an efficient algorithm for finding an item from a sorted list of items. It is defined inside the stdlib.h header file.