Coding

qsort in C: Sort Arrays with a Comparator Function

qsort in C is the standard library function that sorts an array in place: you give it the array, the number of elements, the size of one element and a comparator function that says which of two elements comes first. It is declared in <stdlib.h> and works on any element type, because it only ever sees raw memory and the size you tell it.

The signature

As cppreference documents it, the declaration is:

void qsort(void *ptr, size_t count, size_t size,
           int (*comp)(const void *, const void *));
  • ptr is a pointer to the first element of the array.
  • count is the number of elements.
  • size is the size of one element in bytes, so sizeof(int) or sizeof(arr[0]).
  • comp is the comparison function.

qsort returns nothing and sorts in ascending order according to your comparator. Because it is generic, the comparator receives const void * pointers, and your job is to cast them back to pointers to your real element type.

What the comparator must return

The man page states the rule: the comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. The exact value does not matter, only its sign. The comparator must not modify the objects it is given, and it must return consistent results when called for the same objects, regardless of where they sit in the array. A comparator that gives contradictory answers, for example saying A is before B and B is before A, is outside what the standard library promises, so the result is unpredictable.

Sort an array of ints

This is the pattern almost every qsort call follows. The comparator casts both pointers, reads the values and compares them with explicit tests:

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

static int compare_ints(const void *left, const void *right)
{
    int a = *(const int *)left;
    int b = *(const int *)right;

    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
}

int main(void)
{
    int values[] = {42, -7, 19, 0, 19, 3};
    size_t count = sizeof values / sizeof values[0];

    qsort(values, count, sizeof values[0], compare_ints);

    for (size_t i = 0; i < count; i++) {
        printf("%d ", values[i]);
    }
    printf("\n");
    return 0;
}

Example output:

-7 0 3 19 19 42

Passing sizeof values[0] instead of sizeof(int) keeps the call correct if you later change the element type. Computing count with sizeof values / sizeof values[0] only works where values is a real array. Once an array is passed to a function it decays to a pointer, and the same expression gives the wrong answer, so pass the count along explicitly. The article on arrays in C covers that decay in detail.

Why return a - b is a bug

You will see comparators written as return a - b; because it is short. Do not copy it. If a is INT_MIN and b is positive, the subtraction overflows, and signed integer overflow is undefined behavior in C. The cppreference example marks exactly this shortcut as erroneous. Even when it does not crash, an overflowed result can have the wrong sign and put elements in the wrong order. Use the explicit tests above, or the compact form the same page lists as a possible shortcut:

return (a > b) - (a < b);

Each comparison yields 0 or 1, so the result is -1, 0 or 1 with no overflow possible.

Sort in descending order

Swap the operands inside the comparator rather than negating a subtraction:

static int compare_ints_desc(const void *left, const void *right)
{
    int a = *(const int *)left;
    int b = *(const int *)right;

    return (b > a) - (b < a);
}

Now the larger value compares as "less", so it lands first. Calling qsort(values, count, sizeof values[0], compare_ints_desc) on the array above gives 42 19 19 3 0 -7.

Sort doubles

The same pattern works for floating point, and it is one place where the subtraction trick fails for a second reason: the difference of two doubles is a double, and converting a small difference such as 0.5 to int truncates it to 0, which means "equal". Always compare with < and >:

static int compare_doubles(const void *left, const void *right)
{
    double a = *(const double *)left;
    double b = *(const double *)right;

    return (a > b) - (a < b);
}

If the array can contain NaN, this comparator treats NaN as equal to everything, which breaks the consistency rule above. Remove NaN values first or decide explicitly where they should go. For background on why doubles behave this way, see double in C.

Sort an array of strings

An array of char * is the case that trips people up. The elements being compared are the char * values, so the comparator receives pointers to char *, in other words pointers to pointers to char. The man page's own example spells this out. You cast, dereference once, and then call strcmp:

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

static int compare_strings(const void *left, const void *right)
{
    const char *a = *(const char *const *)left;
    const char *b = *(const char *const *)right;

    return strcmp(a, b);
}

int main(void)
{
    const char *names[] = {"pear", "apple", "fig", "banana"};
    size_t count = sizeof names / sizeof names[0];

    qsort(names, count, sizeof names[0], compare_strings);

    for (size_t i = 0; i < count; i++) {
        printf("%s\n", names[i]);
    }
    return 0;
}

Example output:

apple
banana
fig
pear

Passing strcmp straight to qsort is wrong for this array, because strcmp would be handed the address of each pointer, not the string. It also has the wrong parameter types for the qsort prototype. Wrap it as shown. strcmp compares byte values, so uppercase letters sort before lowercase ones; the article on strcmp in C explains what it returns and how to handle case. If your strings live in a two-dimensional char array instead, each element is a fixed-size row, so pass the row length as the element size and compare with strcmp((const char *)left, (const char *)right).

Sort an array of structs

For structs, cast to a pointer to the struct and compare the field you want. To sort by more than one field, return the first non-zero result:

struct person {
    const char *name;
    int age;
};

static int compare_people(const void *left, const void *right)
{
    const struct person *a = left;
    const struct person *b = right;

    if (a->age != b->age) {
        return (a->age > b->age) - (a->age < b->age);
    }
    return strcmp(a->name, b->name);
}

This sorts by age first, and people with the same age by name. In C you can assign a void * to any object pointer type without a cast, so const struct person *a = left; is valid. Sorting structs moves whole structs around, so for large structs it can be cheaper to sort an array of pointers to them and compare through the pointer. See struct in C for how to declare and initialize the array.

qsort is not guaranteed to be stable

If two elements compare as equal, their order in the sorted array is unspecified. cppreference goes further: despite the name, neither C nor POSIX requires qsort to be implemented with quicksort, or to make any complexity or stability guarantees. A given C library may happen to preserve the order of equal elements today, and a different one, or a later version, may not, so never depend on it. If you need stable behavior, store each element's original position in the data and make it the last tie-breaker in the comparator. The multi-field struct comparator above is the same idea.

Passing extra data: qsort_r and qsort_s

Plain qsort gives the comparator nothing except the two element pointers, so you cannot pass a sort direction or a lookup table without a global variable. Two extensions add a context pointer. glibc's qsort_r passes a third void *arg to the comparator, and it needs _GNU_SOURCE defined. C11 Annex K defines qsort_s with a similar context argument, but it is only guaranteed to exist if __STDC_LIB_EXT1__ is defined and you define __STDC_WANT_LIB_EXT1__ to 1 before including <stdlib.h>. Microsoft's qsort_s differs from the standard one: its comparator takes the context as the first parameter. Code that needs to build on several platforms is usually simpler if it avoids both and sorts with a plain comparator.

Common mistakes

  • Wrong element size. Passing sizeof(arr) instead of sizeof(arr[0]) makes qsort treat the array as one giant element, or step through memory in the wrong strides.
  • Wrong count for a pointer. sizeof ptr / sizeof ptr[0] on a pointer parameter gives the pointer size divided by the element size, not the array length. Pass the length separately.
  • Casting to the wrong type. Reading a double element as int * compiles without a warning, because the parameters are void *, and sorts garbage.
  • Forgetting the extra dereference for strings. The comparator for char * elements receives char **, as shown above.
  • A comparator that modifies its arguments or uses changing state. It must be consistent for the same objects wherever they are in the array.

The same void * cast patterns appear throughout C. If they still feel unfamiliar, pointers in C is a good place to review them.

Frequently asked questions

Does qsort in C use quicksort?
Not necessarily. The name suggests it, but neither the C nor the POSIX standard requires an implementation to use quicksort, or to make any guarantee about complexity or stability. What you can rely on is that the array ends up sorted according to your comparator.
Is qsort stable?
No guarantee is made. If two elements compare as equal, their order in the sorted array is unspecified. If you need equal elements to keep their original order, add the original index to the data and use it as a tie-breaker in the comparator.
How do I sort in descending order with qsort?
Reverse the comparison in your comparator: return a positive number when the first element is smaller than the second. Do not negate the result of a subtraction, because that can overflow. Swap the operands of the comparison instead.
Why is returning a - b a bad comparator for ints?
Subtracting two ints can overflow, for example INT_MIN minus a positive number, and signed overflow is undefined behavior in C. The cppreference example labels this shortcut erroneous. Compare with less-than and greater-than instead.
How do I pass extra data to the comparator?
Standard qsort has no extra argument. glibc offers qsort_r, which takes a third pointer that is passed to the comparator, but it needs _GNU_SOURCE. C11 Annex K defines qsort_s with a context argument, but it is optional, and the Windows version of qsort_s orders its comparator parameters differently.

Sources