Skip to main content

Lesson 5 of 5

Mini Project Part 10 - Generic Sort with Function Pointers

Build a generic merge sort that can sort any array using a function pointer comparator - mirroring the `qsort` signature but with a cleaner implementation. Then create a type-safe wrapper using macros. Applies: function pointers, void* arithmetic workaround, malloc for temporary merge buffer.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Generic Merge Sort - Function Pointer Comparator

Generic Merge Sort - Function Pointer Comparator
/* msort.c - generic merge sort */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int (*CmpFn)(const void *a, const void *b);

/* Merge two sorted sub-arrays */
static void merge(char *arr, size_t lo, size_t mid, size_t hi,
                  size_t elem_size, CmpFn cmp, char *buf) {
    size_t i = lo, j = mid, k = 0;
    while (i < mid && j < hi) {
        const void *a = arr + i * elem_size;
        const void *b = arr + j * elem_size;
        if (cmp(a, b) <= 0) { memcpy(buf + k*elem_size, a, elem_size); i++; }
        else                 { memcpy(buf + k*elem_size, b, elem_size); j++; }
        k++;
    }
    while (i < mid) { memcpy(buf+k*elem_size, arr+i*elem_size, elem_size); i++; k++; }
    while (j <  hi) { memcpy(buf+k*elem_size, arr+j*elem_size, elem_size); j++; k++; }
    memcpy(arr + lo*elem_size, buf, k*elem_size);
}

static void msort_rec(char *arr, size_t lo, size_t hi,
                       size_t elem_size, CmpFn cmp, char *buf) {
    if (hi - lo <= 1) return;
    size_t mid = lo + (hi - lo) / 2;
    msort_rec(arr, lo,  mid, elem_size, cmp, buf);
    msort_rec(arr, mid, hi,  elem_size, cmp, buf);
    merge(arr, lo, mid, hi, elem_size, cmp, buf);
}

int generic_sort(void *base, size_t count, size_t elem_size, CmpFn cmp) {
    if (count <= 1) return 0;
    char *buf = malloc(count * elem_size);
    if (!buf) return -1;
    msort_rec((char *)base, 0, count, elem_size, cmp, buf);
    free(buf);
    return 0;
}

/* Comparators */
int cmp_int(const void *a, const void *b) {
    int ia = *(const int*)a, ib = *(const int*)b;
    return (ia > ib) - (ia < ib);
}
int cmp_str(const void *a, const void *b) {
    return strcmp(*(const char**)a, *(const char**)b);
}
typedef struct { char name[32]; int age; } Person;
int cmp_person_age(const void *a, const void *b) {
    const Person *pa = a; const Person *pb = b;
    return pa->age - pb->age;
}

int main(void) {
    int nums[] = {5,-3,8,1,0,7,-1,4};
    int n = 8;
    generic_sort(nums, n, sizeof(int), cmp_int);
    for (int i = 0; i < n; i++) printf("%d ", nums[i]);
    printf("
");

    const char *words[] = {"banana","apple","mango","cherry"};
    generic_sort(words, 4, sizeof(char*), cmp_str);
    for (int i = 0; i < 4; i++) printf("%s ", words[i]);
    printf("
");

    Person people[] = {{"Alice",30},{"Bob",25},{"Carol",35},{"Dave",28}};
    generic_sort(people, 4, sizeof(Person), cmp_person_age);
    for (int i = 0; i < 4; i++) printf("%s(%d) ", people[i].name, people[i].age);
    printf("
");

    return 0;
}
/* Build: gcc -Wall -Wextra -std=c99 msort.c -o msort */

Common Mistakes

  • Using `void* + i` for pointer arithmetic - `void*` pointer arithmetic is not standard C (gcc allows it as an extension, treating sizeof(void)==1). Always cast to `char*` first: `(char*)base + i * elem_size`.
  • Allocating the merge buffer inside the recursive function - allocating/freeing on every merge call causes O(n log n) allocations. Allocate once before the recursion and pass it as a parameter.
  • Comparator returning subtraction for integers - `return *(int*)a - *(int*)b` overflows for `INT_MIN - 1`. Use the safe `(a>b)-(a<b)` pattern.

Tip

Tip

Practice Mini Project Part 10 Generic Sort with Function Pointers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Generic sorting algorithm sorts arbitrary data types using comparison callback function pointers

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 10 Generic Sort with Function Pointers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 10 Generic Sort with Function Pointers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Build a generic merge sort that can sort any array using a function pointer comparator - mirroring the `qsort` signature but with a cleaner implementation.
  • Using `void* + i` for pointer arithmetic - `void*` pointer arithmetic is not standard C (gcc allows it as an extension, treating sizeof(void)==1). Always cast to `char*` first: `(char*)base + i * elem_size`.
  • Allocating the merge buffer inside the recursive function - allocating/freeing on every merge call causes O(n log n) allocations. Allocate once before the recursion and pass it as a parameter.
  • Comparator returning subtraction for integers - `return *(int*)a - *(int*)b` overflows for `INT_MIN - 1`. Use the safe `(a>b)-(a<b)` pattern.

Topics in This Module

0/5 done