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

Using C library 'qsort' function

Using C library 'qsort' function

What you'll learn: How to use the built-in C standard library function to efficiently sort any type of data array.

The "Swiss Army Knife" of Sorting

Writing a QuickSort algorithm from scratch is a great academic exercise, but in the real world, C provides a highly optimized version via the <stdlib.h> header called qsort.

Think of qsort like a professional organizing service. You don't need to tell them how to move the boxes around (the sorting logic); you just need to give them the keys to the room and a rulebook that explains which box is "heavier" than the other. Because qsort is designed to work with any data—integers, floats, or even complex custom structs—it uses a "callback function" to understand your data.

The Comparison Rulebook

The most important part of using qsort is the comparison function. This function takes two pointers, compares the values they point to, and returns:

  • A negative number if the first item comes before the second.
  • Zero if they are equal.
  • A positive number if the first item comes after the second.

Putting it into Practice

To use qsort, you provide four things: the array, the number of elements, the size of one element, and your comparison function.

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

// The comparison function for integers
int compare(const void *a, const void *b) {
    // Cast the void pointers to integer pointers and dereference them
    int valA = *(int*)a;
    int valB = *(int*)b;
    
    return (valA - valB); 
}

int main() {
    int numbers[] = {42, 7, 101, 12, 5};
    int n = sizeof(numbers) / sizeof(numbers[0]);

    // qsort(array, count, size_of_element, comparison_function)
    qsort(numbers, n, sizeof(int), compare);

    for(int i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    
    return 0;
}

Why use void pointers?

You'll notice the comparison function uses const void *a. In C, a void* is a generic pointer. It’s the language's way of saying, "I’m pointing to something in memory, but I don't know if it's an integer or a character." Inside the function, you tell C what the data is by "casting" it back to an int*, allowing qsort to remain flexible enough to sort anything.

Key takeaway

The qsort function saves you from reinventing the wheel by requiring only a custom comparison function to sort any array.