CKTIS / C
sorting and comparison — concept C23
Sorting requires a consistent ordering relation; a `qsort` comparator returns negative, zero, or positive and should not subtract integers when subtraction may overflow. `qsort` does not guarantee stability.
Version: C23
Syntax
sorting and comparisonSorting requires a consistent ordering relation; a qsort comparator returns negative, zero, or positive and should not subtract integers when subtraction may overflow. qsort does not guarantee stability.
For qsort, cast both const void * arguments to the correct type and return (a > b) - (a < b), avoiding subtraction overflow. If stability is required, store the original index as another key or use a stable algorithm of your own.
Test an empty array, one element, duplicates, extreme values, and already sorted data. The comparator must remain deterministic and consistent for the whole call; modifying elements, depending on changing state, or treating NaN inconsistently breaks the ordering.
Examples
#include <stdio.h>
#include <stdlib.h>
static int compare_int(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); }
int main(void) { int values[] = {3, 1, 2}; qsort(values, 3, sizeof values[0], compare_int); printf("%d%d%d\n", values[0], values[1], values[2]); return 0; }
Result
123
Sorting requires a consistent ordering relation; a `qsort` comparator returns negative, zero, or positive and should not subtract integers when subtraction may overflow. `qsort` does not guarantee stability.