Open In App

How to Use bsearch with an Array of Struct in C?

The bsearch function in C is a standard library function defined in the stdlib.h header file that is used to perform binary search on array-like structure. In this article, we will learn to use bsearch with an array of struct in C.

Input:
struct Person people[] = { { 1, "Ram" }, { 2, "Rohan" }, { 4, "Ria" }, { 3, "Mohan" } };
Key: 3

Output:
Person found: ID = 3
Name = Mohan

bsearch on Array of Structure in C

To use std::bsearch() with an array of structure, we have to first sort the given array of structs and then write a comparator function that helps the bsearch to find the matching value. After that, we can call the std::bsearch that returns a pointer to the element if it is found otherwise it will return NULL.



Syntax of search()

bsearch(keyToFind, arrayName, arraySize, sizeof(struct structName), compareFunction);

Here,

C Program to Use bsearch with a Array of Struct

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






// C Program to illustrate how to use bsearch with a
// structure
#include <stdio.h>
#include <stdlib.h>
  
// Define the Person struct
struct Person {
    int id;
    char name[50];
};
  
// Comparison function for bsearch
int comparePersons(const void* a, const void* b)
{
    // Convert the void pointers to Person pointers
    int idA = ((struct Person*)a)->id;
    int idB = ((struct Person*)b)->id;
  
    // Compare the IDs for sorting
    return (idA - idB);
}
  
int main()
{
    // Array of Person structs (assumed to be sorted by id)
    struct Person people[] = {
        { 1, "Ram" },
        { 2, "Rohan" },
        { 4, "Ria" },
        { 3, "Mohan" },
    };
  
    // Calculate the number of elements in the array
    int n = sizeof(people) / sizeof(people[0]);
  
    // Sort the array before using bsearch
    qsort(people, n, sizeof(struct Person), comparePersons);
  
    // Define the key to search for
    struct Person keyPerson = {
        .id = 3, .name = ""
    }; // Using designated initializer for clarity
  
    // Use bsearch to find the person with the specified ID
    struct Person* result = (struct Person*)bsearch(
        &keyPerson, people, n, sizeof(struct Person),
        comparePersons);
  
    // Check if the person was found
    if (result != NULL) {
        printf("Person found: ID=%d, Name=%s\n", result->id,
               result->name);
    }
    else {
        printf("Person not found.\n");
    }
  
    return 0;
}

Output
Person found: ID=3, Name=Mohan

Time complexity: O(log⁡(N)), where N is the number of elements in the array of structs.
Auxilliary Space: O(1)


Article Tags :