Searching in Struct
Introduction
In C, structures (struct
) allow grouping different types of data together. Sometimes, we need to search for specific records inside an array of structures. This module explains how to perform searching operations on an array of structures in C using both Linear Search and Binary Search.
Defining a Structure
Before searching, let's define a simple structure to store student information:
#include <stdio.h>
#include <string.h>
#define SIZE 5
struct Student {
int id;
char name[20];
float grade;
};
Here, the Student
struct contains three fields:
-
id
: an integer representing the student ID. -
name
: a character array storing the student's name. -
grade
: a floating-point number representing the student's grade.
Linear Search on Struct Array
Linear search iterates through each element in the struct array until a match is found.
Example: Searching for a Student by Name
int main() {
struct Student students[SIZE] = {
{101, "Alice", 85.5},
{102, "Bob", 78.0},
{103, "Charlie", 92.0},
{104, "David", 88.5},
{105, "Eve", 90.0}
};
char searchName[20];
int found = 0;
printf("Enter student name to search: ");
scanf("%s", searchName);
for (int i = 0; i < SIZE; i++) {
if (strcmp(students[i].name, searchName) == 0) {
printf("Student found: ID=%d, Name=%s, Grade=%.2f\n", students[i].id, students[i].name, students[i].grade);
found = 1;
break;
}
}
if (!found) {
printf("Student not found!\n");
}
return 0;
}
Output Example:
Enter student name to search: Bob
Student found: ID=102, Name=Bob, Grade=78.00
Binary Search on Struct Array
Binary search is faster than linear search but requires the array to be sorted. It repeatedly divides the array into halves to locate the desired element.
Example: Searching for a Student by ID (Binary Search)
int binarySearch(struct Student students[], int left, int right, int key) {
while (left <= right) {
int mid = (left + right) / 2;
if (students[mid].id == key)
return mid;
if (students[mid].id < key)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
int main() {
struct Student students[SIZE] = {
{101, "Alice", 85.5},
{102, "Bob", 78.0},
{103, "Charlie", 92.0},
{104, "David", 88.5},
{105, "Eve", 90.0}
};
int searchID;
printf("Enter student ID to search: ");
scanf("%d", &searchID);
int result = binarySearch(students, 0, SIZE - 1, searchID);
if (result != -1)
printf("Student found: ID=%d, Name=%s, Grade=%.2f\n", students[result].id, students[result].name, students[result].grade);
else
printf("Student not found!\n");
return 0;
}
Output Example:
Enter student ID to search: 103
Student found: ID=103, Name=Charlie, Grade=92.00
Conclusion
- Linear Search is simple and works on unsorted data but is slower for large datasets.
- Binary Search is much faster but requires the array to be sorted.
- The
strcmp
function is useful for searching strings within structures.