Course contentsShow
← C
Lesson 1060 of 1,21914. Data Structures in CFree lesson

Writing a custom comparator for qsort

Writing a custom comparator for qsort

What you'll learn: How to create a specialized function that tells the built-in qsort exactly how to order your unique data.

The Judge in the Box

Imagine you have a deck of cards, but instead of numbers, they have complex recipes written on them. You want to sort them by "difficulty." You hire a professional organizer (the qsort function) to do the work. The organizer is incredibly fast at moving cards around, but they have no idea what a "recipe" is or how to measure "difficulty."

To make it work, you must provide a Comparator. Think of this as a tiny judge sitting in a box. Whenever the organizer holds up two cards, they show them to the judge and ask: "Which one comes first?" The judge gives a simple answer: "The left one," "The right one," or "They are equal."

In C, qsort handles the heavy lifting of the sorting algorithm, but it relies on your custom function to make the actual comparisons.

The Comparison Logic

A comparator function must follow a specific signature. It takes two generic pointers (void *) and returns an integer:

  • Negative: The first item should come before the second.
  • Zero: The items are effectively equal.
  • Positive: The first item should come after the second.

Because the pointers are void *, you must "cast" them back to your specific data type inside the function so C knows what it's looking at.

Seeing it in Action

Here is how you would sort an array of integers in descending order (largest to smallest) by writing a custom comparator:

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

// The "Judge" function
int compareDescending(const void *a, const void *b) {
    // 1. Cast the generic pointers to integer pointers
    int valA = *(int*)a;
    int valB = *(int*)b;

    // 2. Logic: Return positive if B is greater than A to flip the order
    if (valA < valB) return 1;
    if (valA > valB) return -1;
    return 0;
}

int main() {
    int numbers[] = {15, 42, 7, 89, 23};
    int n = 5;

    // qsort(array, count, size_of_element, comparator)
    qsort(numbers, n, sizeof(int), compareDescending);

    for(int i = 0; i < n; i++) {
        printf("%d ", numbers[i]); // Output: 89 42 23 15 7
    }
    
    return 0;
}

Why This Matters

This pattern is incredibly powerful. You aren't limited to numbers; you can write comparators that sort a list of Student structs by GPA, or sort strings by their length rather than their alphabetical order. By separating the sorting logic from the comparison logic, C allows you to sort anything you can define.

Key takeaway

A comparator function bridges the gap between qsort and your data by returning a negative, zero, or positive integer to define order.