typestar

qsort with a comparator in C

The standard sort takes element size and a comparison function.

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

static int by_int(const void *a, const void *b) {
    int x = *(const int *) a;
    int y = *(const int *) b;
    return (x > y) - (x < y);
}

static int by_length(const void *a, const void *b) {
    size_t x = strlen(*(const char *const *) a);
    size_t y = strlen(*(const char *const *) b);
    return (x > y) - (x < y);
}

void sort_both(int *nums, size_t n, const char **words, size_t w) {
    qsort(nums, n, sizeof(int), by_int);
    qsort(words, w, sizeof(char *), by_length);
}

How it works

  1. The comparator receives const void * and casts them back.
  2. It returns negative, zero or positive — not a bool.
  3. Never subtract: size_t underflows and int can overflow.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
494
Tokens
168
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 4 of 4 in Generic & function pointers, step 9 of 25 in Pointers & memory.

← Previous Next →