Our example demonstrates custom sorting in C. We’ll sort strings by their length and a custom struct by age.
In this C example, we use the standard library’s qsort function to perform custom sorting. We define comparison functions that determine the order of elements.
For sorting strings by length, we implement compare_string_lengths. This function compares the lengths of two strings using strlen.
To sort custom structs, we define a Person struct with name and age fields. We then implement compare_person_ages to compare Person structs based on their age field.
In the main function, we demonstrate sorting both an array of strings (fruits) and an array of Person structs. We use qsort with the appropriate comparison function for each case.
Note that C doesn’t have built-in dynamic arrays or slices like some higher-level languages. We use fixed-size arrays in this example for simplicity. In a real-world scenario, you might want to use dynamic memory allocation for more flexibility.
To compile and run this program:
This example demonstrates how to implement custom sorting logic in C using the standard library’s qsort function and custom comparison functions.