C Online Compiler
Example: qsort Structs by ID in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// qsort Structs by ID #include <stdio.h> #include <stdlib.h> // For qsort #include <string.h> // For strcpy // Define a custom structure typedef struct { int id; char name[50]; float score; } Student; // Comparison function to sort Students by ID (ascending) int compareStudentsByID(const void *a, const void *b) { // Cast void* to Student* and dereference to access members const Student *student_a = (const Student *)a; const Student *student_b = (const Student *)b; return student_a->id - student_b->id; // Compare IDs } // Comparison function to sort Students by Name (alphabetical) int compareStudentsByName(const void *a, const void *b) { const Student *student_a = (const Student *)a; const Student *student_b = (const Student *)b; return strcmp(student_a->name, student_b->name); // Compare names using strcmp } void printStudents(const char *msg, Student students[], int n) { printf("%s:\n", msg); for (int i = 0; i < n; i++) { printf(" ID: %d, Name: %s, Score: %.1f\n", students[i].id, students[i].name, students[i].score); } printf("\n"); } int main() { // Step 1: Initialize an array of Student structures Student students[] = { {103, "Alice", 85.5}, {101, "Bob", 92.0}, {105, "Charlie", 78.0}, {102, "David", 88.5}, {104, "Eve", 95.0} }; int n = sizeof(students) / sizeof(students[0]); printStudents("Original student list", students, n); // Step 2: Sort students by ID qsort(students, n, sizeof(Student), compareStudentsByID); printStudents("Sorted students by ID", students, n); // Step 3: Sort students by Name (using the same array) qsort(students, n, sizeof(Student), compareStudentsByName); printStudents("Sorted students by Name", students, n); return 0; }
Output
Clear
ADVERTISEMENTS