#include <stdio.h>
#include <stdlib.h>
// Example structure representing an arbitrary/unspecified data type
typedef struct {
int id;
char name[32];
} Item;
/**
* Comparison function required by bsearch.
* Compares two Item elements by their ID.
*
* @return Negative if a < b, 0 if a == b, Positive if a > b.
*/
int compare_items(const void *a, const void *b) {
const Item *item_a = (const Item *)a;
const Item *item_b = (const Item *)b;
return (item_a->id - item_b->id);
}
/**
* Generic wrapper function for bsearch to find an element in a sorted array.
*
* @param key Pointer to the target element being searched for.
* @param base Pointer to the first element of the array.
* @param nitems Number of elements in the array.
* @param size Size of each individual element in bytes.
* @return Pointer to the matched element, or NULL if not found.
*/
void* find_element(const void *key, const void *base, size_t nitems, size_t size,
int (*compar)(const void *, const void *)) {
// bsearch performs a binary search on the sorted array
return bsearch(key, base, nitems, size, compar);
}
int main(void) {
// The array MUST be sorted prior to calling bsearch
Item inventory[] = {
{101, "Laptop"},
{205, "Mouse"},
{310, "Keyboard"},
{420, "Monitor"}
};
size_t num_items = sizeof(inventory) / sizeof(inventory[0]);
// Define the key we are looking for
Item search_key = {310, ""};
// Call our search wrapper function
Item *result = (Item *)find_element(&search_key, inventory, num_items, sizeof(Item), compare_items);
if (result != NULL) {
printf("Found item: ID = %d, Name = %s\n", result->id, result->name);
} else {
printf("Item not found.\n");
}
return 0;
}
/*
run:
Found item: ID = 310, Name = Keyboard
*/