How to Use bsearch with an Array of Struct in C? Last Updated : 01 Mar, 2024 Comments Improve Suggest changes Like Article Like Report 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 = Mohanbsearch on Array of Structure in CTo 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 valuesC Program to Use bsearch with a Array of StructThe 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) Comment More infoAdvertise with us Next Article How to Use bsearch with an Array of Struct in C? C chintantogadiya Follow Improve Article Tags : C Programs C Language Binary Search C Examples Practice Tags : Binary Search Similar Reads C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used 5 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this, 9 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read Like