Sorting structs by multiple fields
What you'll learn: How to create a tie-breaking logic in your comparison functions to sort complex data by more than one criteria.
The "Tie-Breaker" Logic
When using qsort() to sort basic numbers, the logic is simple: is A bigger than B? However, real-world data is rarely that simple. Imagine you are sorting a list of students. You want to sort them primarily by their Grade (highest first), but if two students have the same grade, you want to sort them alphabetically by Name.
In programming, we call this "lexicographical" or "multi-level" sorting. The secret lies entirely within your comparison function. You check your primary field first; if the items are not equal, you return the result immediately. If they are equal, you "break the tie" by moving on to the secondary field.
Implementing the Comparison
Think of this like a flowchart. You only look at the second piece of information if the first piece fails to give you a clear winner. If you were sorting mail, you’d look at the Zip Code first. If two letters have the same Zip Code, only then would you look at the street name.
Here is how you write that logic in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char name[50];
int grade;
};
int compareStudents(const void *a, const void *b) {
struct Student *studentA = (struct Student *)a;
struct Student *studentB = (struct Student *)b;
// 1. Check primary field: Grade (Descending)
if (studentB->grade != studentA->grade) {
return studentB->grade - studentA->grade;
}
// 2. Tie-breaker: Name (Alphabetical)
// strcmp returns 0 if strings are equal, negative if A < B, positive if A > B
return strcmp(studentA->name, studentB->name);
}
How it works
- The Primary Check: The function first subtracts grades. If one student has a 95 and the other an 88, the result is non-zero,
qsortmoves them, and the function finishes. - The "If" Gate: The
ifstatement acts as a gatekeeper. It only allows the code to reach thestrcmpline if the grades are identical (a tie). - The Final Word: Once the tie-breaker runs, it provides the final decision to
qsort. You can chain as many of these as you like—sorting by Grade, then Last Name, then First Name, and so on.
Key takeaway
To sort by multiple fields, check your primary field first and only return a comparison of the secondary field if the primary fields are equal.