C qsort
qsort rearranges an array in place using a comparator that returns a negative, zero, or positive integer for each pair.
A simple example
qsort
- Start with 3, 1, 2
- Do this Sort by increasing numeric value
- Result 1, 2, 3
Syntax
qsort(items, count, sizeof items[0], compare)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Sort signed readings including extreme values
A batch can contain enough readings, or large enough values, to exceed a simple implementation's assumptions. Select a safe representation or comparison before combining, storing or ordering those inputs.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
static int compare(const void *left, const void *right) {
int a = *(const int *)left;
int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void) {
int readings[] = {INT_MAX, 7, INT_MIN, 7};
qsort(readings, 4, sizeof readings[0], compare);
if (readings[0] == INT_MIN && readings[1] == 7 &&
readings[2] == 7 && readings[3] == INT_MAX) {
puts("sorted extremes and duplicates");
}
return 0;
}
sorted extremes and duplicates
Subtracting one signed integer from the other can overflow. Comparing with greater-than and less-than produces the required signs even at the limits of int. Tied elements can change relative order.
Open Group function reference for qsort
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?
Review print quantities
A print room records four job quantities, including a cancelled job. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?