Sorting by Functions in C

Our example demonstrates custom sorting in C. We’ll sort strings by their length and a custom struct by age.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Custom comparison function for string lengths
int compare_string_lengths(const void *a, const void *b) {
    return strlen(*(const char **)a) - strlen(*(const char **)b);
}

// Person struct definition
typedef struct {
    char name[20];
    int age;
} Person;

// Custom comparison function for Person ages
int compare_person_ages(const void *a, const void *b) {
    return ((Person *)a)->age - ((Person *)b)->age;
}

int main() {
    // Sorting strings by length
    const char *fruits[] = {"peach", "banana", "kiwi"};
    int fruits_count = sizeof(fruits) / sizeof(fruits[0]);

    qsort(fruits, fruits_count, sizeof(char *), compare_string_lengths);

    printf("Sorted fruits by length: ");
    for (int i = 0; i < fruits_count; i++) {
        printf("%s ", fruits[i]);
    }
    printf("\n");

    // Sorting custom structs by age
    Person people[] = {
        {"Jax", 37},
        {"TJ", 25},
        {"Alex", 72}
    };
    int people_count = sizeof(people) / sizeof(people[0]);

    qsort(people, people_count, sizeof(Person), compare_person_ages);

    printf("Sorted people by age: ");
    for (int i = 0; i < people_count; i++) {
        printf("{%s %d} ", people[i].name, people[i].age);
    }
    printf("\n");

    return 0;
}

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:

$ gcc -o sorting_example sorting_example.c
$ ./sorting_example
Sorted fruits by length: kiwi peach banana 
Sorted people by age: {TJ 25} {Jax 37} {Alex 72}

This example demonstrates how to implement custom sorting logic in C using the standard library’s qsort function and custom comparison functions.