Using C library 'bsearch' function
What you'll learn: How to use the built-in C standard library function to instantly perform an efficient binary search on sorted arrays.
Why use a library function?
Up until now, you might have been writing your own loops to search through data. While writing a manual binary search is a great logic exercise, C provides a high-performance, pre-tested tool called bsearch in the <stdlib.h> library. Think of it like using a professional GPS instead of drawing your own map; it’s faster, handles the tricky edge cases, and works on any type of data—from integers to complex structures.
How bsearch works
The bsearch function is a "generic" searcher. Because it doesn't know if you are searching for numbers or text, it requires four specific pieces of information:
- The Key: What you are looking for.
- The Base: The array to search.
- Dimensions: How many elements are in the array and how big each one is.
- The Comparator: A small "helper" function you write that tells C how to compare two items (just like the one used in
qsort).
Important: For bsearch to work, your array must already be sorted. If it isn't, the algorithm will get lost and return nothing.
See it in action
Here is how you search for an integer in a sorted list:
#include <stdio.h>
#include <stdlib.h>
// The comparator: returns 0 if match, negative if a < b, positive if a > b
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int data[] = {10, 22, 35, 47, 50, 68, 99}; // Must be sorted!
int target = 47;
int num_elements = 7;
// bsearch returns a pointer to the found item, or NULL if not found
int *item = bsearch(&target, data, num_elements, sizeof(int), compare);
if (item != NULL) {
printf("Found %d at memory address %p\n", *item, (void*)item);
} else {
printf("Item not found.\n");
}
return 0;
}
Understanding the pointer result
Unlike a manual loop that usually returns an index (like i), bsearch returns a pointer to the element inside the array. If the item isn't there, it returns NULL. This makes it incredibly flexible for working with arrays of pointers or large structs where you want to access the data directly once located.
Key takeaway
The bsearch function provides a standardized, efficient way to search sorted arrays by using a custom comparator function to navigate the data.