How to Sort an Array of Structs Based on a Member in C?
Last Updated :
19 Feb, 2024
In C, we may sometimes need to sort the array of structs based on the values of certain members. In this article, we will learn how to sort a given array of structures based on a specific member in C.
For Example,
Input:
myArrayofStructs[] = {{"Person1", 21, 160.5},
{"Person2", 20, 175.0},
{"Person3", 22, 165.5}};
Output:
Sorted array based on age:
Person2, 20, 175.0
Person1, 21, 160.5
Person3, 22, 165.5
Sorting Array of Structure based on a Member in C
To sort an array of structures based on a specific member, we can use the qsort() library function. Pass a pointer to an array, the number of elements, the size of each element, and a comparison function that tells qsort how to compare two structs based on that members.
C Program to Sort an Array of Structure based on Specific Member
The below example demonstrates how we can sort an array of structures on the basis of certain members using qsort in C.
C
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
int compareByAge( const void * a, const void * b)
{
return (( struct Person*)a)->age
- (( struct Person*)b)->age;
}
int main()
{
struct Person people[] = { { "Person1" , 21, 160.5 },
{ "Person2" , 20, 175.0 },
{ "Person3" , 22, 165.5 } };
int n = sizeof (people) / sizeof (people[0]);
qsort (people, n, sizeof ( struct Person), compareByAge);
printf ( "Sorted array based on age:\n" );
for ( int i = 0; i < n; i++) {
printf ( "%s, %d, %.1f\n" , people[i].name,
people[i].age, people[i].height);
}
return 0;
}
|
Output
Sorted array based on age:
Person2, 20, 175.0
Person1, 21, 160.5
Person3, 22, 165.5
Time Complexity: O(n log n), time complexity of the quicksort algorithm used by qsort()
.
Auxiliary Space: O(log n)
Share your thoughts in the comments
Please Login to comment...