Stable multi-key record sorting with nulls in C
C
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
typedef struct { const char *name; int age; size_t seq; } Row;
static int row_cmp(const void *a, const void *b) {
const Row *x = a, *y = b;
if (!x->name || !y->name) return (x->name == NULL) - (y->name == NULL);
int c = strcmp(x->name, y->name);
if (c) return c;
if (x->age != y->age) return (x->age > y->age) - (x->age < y->age);
return (x->seq > y->seq) - (x->seq < y->seq);
}
void sort_rows(Row *rows, size_t n) {
for (size_t i = 0; i < n; i++) rows[i].seq = i;
qsort(rows, n, sizeof *rows, row_cmp);
}