Sorting in C

Our example demonstrates sorting in C using the standard library’s qsort function. We’ll look at sorting for different data types.

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

// Comparison function for strings
int compare_strings(const void* a, const void* b) {
    return strcmp(*(const char**)a, *(const char**)b);
}

// Comparison function for integers
int compare_ints(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    // Sorting strings
    const char* strs[] = {"c", "a", "b"};
    int strs_len = sizeof(strs) / sizeof(strs[0]);
    qsort(strs, strs_len, sizeof(const char*), compare_strings);
    
    printf("Strings: ");
    for (int i = 0; i < strs_len; i++) {
        printf("%s ", strs[i]);
    }
    printf("\n");

    // Sorting integers
    int ints[] = {7, 2, 4};
    int ints_len = sizeof(ints) / sizeof(ints[0]);
    qsort(ints, ints_len, sizeof(int), compare_ints);
    
    printf("Ints:    ");
    for (int i = 0; i < ints_len; i++) {
        printf("%d ", ints[i]);
    }
    printf("\n");

    // Check if the array is sorted
    int is_sorted = 1;
    for (int i = 1; i < ints_len; i++) {
        if (ints[i] < ints[i-1]) {
            is_sorted = 0;
            break;
        }
    }
    printf("Sorted:  %s\n", is_sorted ? "true" : "false");

    return 0;
}

This C program demonstrates sorting for both strings and integers using the qsort function from the standard library. The qsort function is generic and can work with any data type, provided we supply an appropriate comparison function.

For strings, we use the compare_strings function which utilizes strcmp to compare two strings. For integers, we use the compare_ints function which simply subtracts one integer from another.

After sorting, we print the sorted arrays. Finally, we manually check if the integer array is sorted by comparing each element with its predecessor.

To compile and run this program:

$ gcc -o sorting sorting.c
$ ./sorting
Strings: a b c
Ints:    2 4 7
Sorted:  true

This example demonstrates how to use C’s standard library to perform sorting operations on different data types. While C doesn’t have built-in generic sorting functions like some higher-level languages, the qsort function provides a flexible way to sort various data types.