Open In App

How to Sort an Array of Structs Based on a Member in C?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to sort an array of structure based on specific
// member
#include <stdio.h>
#include <string.h>
  
// Struct representing a person
struct Person {
    char name[50];
    int age;
    float height;
};
  
// Comparison function for sorting based on age
int compareByAge(const void* a, const void* b)
{
    return ((struct Person*)a)->age
           - ((struct Person*)b)->age;
}
  
int main()
{
    // array of structure
    struct Person people[] = { { "Person1", 21, 160.5 },
                               { "Person2", 20, 175.0 },
                               { "Person3", 22, 165.5 } };
    int n = sizeof(people) / sizeof(people[0]);
  
    // Sorting the array based on age using qsort()
    qsort(people, n, sizeof(struct Person), compareByAge);
  
    // Printing the sorted array
    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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads