How to Sort an Array of Structs with qsort in C? (original) (raw)

Last Updated : 19 Feb, 2024

Sorting C arrays of structs becomes important for many kinds of applications and one common library function that may be used for this is qsort. In this article, we will learn how to use qsort() with an array of structs in C.

**For Example,

**Input: struct Person people[] = {{"Person1", 21}, {"Person2", 22}, {"Person3", 20}};

**Output: Sorted Array (by age): Person3 20 Person1 21 Person2 22

Sorting Array of Structure in C

To sort an array of structures using qsort(), we will have to provide the custom comparator function that compares the structures based on their member values.

Approach

C Program to Sort Array of Structure Using qsort

The below example demonstrates how we can sort an array of structs using qsort in C. Here, we are sorting the array based on the age member.

C `

// C Program to sort an Array of Structs using qsort #include <stdio.h> #include <stdlib.h> #include <string.h>

// Struct definition struct Person { char name[30]; int age; };

// Comparison function for qsort int comparePeople(const void* a, const void* b) { return ((struct Person*)a)->age - ((struct Person*)b)->age; }

int main() { // Array of structs struct Person people[] = { { "Person1", 21 }, { "Person2", 22 }, { "Person3", 20 } }; int numPeople = sizeof(people) / sizeof(people[0]);

// Display original array
printf("Original Array:\n");
for (int i = 0; i < numPeople; i++) {
    printf("%s\t%d\n", people[i].name, people[i].age);
}

// Sorting using qsort
qsort(people, numPeople, sizeof(struct Person),
      comparePeople);

// Display sorted array
printf("\nSorted Array (by age):\n");
for (int i = 0; i < numPeople; i++) {
    printf("%s\t%d\n", people[i].name, people[i].age);
}

return 0;

}

`

Output

Original Array: Person1 21 Person2 22 Person3 20

Sorted Array (by age): Person3 20 Person1 21 Person2 22

**Time Complexity: O(n log n), time complexity of the quicksort algorithm used by qsort().
**Auxiliary Space: O(log n)