How to Use bsearch with an Array of Struct in C?
Last Updated :
01 Mar, 2024
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,
- structName is the name of the structure.
- arrayName is the name of sorted array of struct.
- keyToFind is the element we want to search.
- arraySize is the size of each element in the array of struct.
- compareFunction is the function that compares the values
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
// 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;
}
OutputPerson 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)
Similar Reads
How to Use bsearch with an Array in C? 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=15Output:Value 15 found!bsearch() with an Array in CTo use bsearch() on a given arr
2 min read
How to Create an Array of Structs in C? In C, a structure is a user-defined data type that can be used to group items of different types into a single entity while an array is a collection of similar data elements. In this article, we will learn how to create an array of structs in C. Creating an Array of Structs in CTo create an array of
2 min read
How to Access Array of Structure in C? In C, we can create an array whose elements are of struct type. In this article, we will learn how to access an array of structures in C. For Example, Input:myArrayOfStructs = {{'a', 10}, {'b', 20}, {'A', 9}}Output:Integer Member at index 1: 20Accessing Array of Structure Members in CWe can access t
2 min read
How to Pass Array of Structure to a Function in C? An array of structures in C is a data structure that allows us to store multiple records of different data types in a contiguous memory location where each element of the array is a structure. In this article, we will learn how to pass an array of structures from one function to another in C. Passin
2 min read
How to Add an Element to an Array of Structs in C? In C, a struct is a user-defined data type that allows the users to group related data in a single object. An array of structs allows to store multiple structs in contiguous memory locations. In this article, we will learn how to add an element to an array of structs in C. Example: Input: structArra
3 min read
How to Write a Struct to a Binary File in C? C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C. Writing Structure into a Binary File in CTo write a struct to a binary file, we can use the fwrite() function
2 min read