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
- The comparator receives
const void *and casts them back. - It returns negative, zero or positive — not a bool.
- Never subtract:
size_tunderflows andintcan overflow.
Keywords and builtins used here
by_intby_lengthcharconstintreturnsize_tsizeofsort_bothstaticvoid
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.
Step 4 of 4 in Generic & function pointers, step 9 of 25 in Pointers & memory.