Library contents

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

  1. Start with 3, 1, 2
  2. Do this Sort by increasing numeric value
  3. Result 1, 2, 3
The comparison rule puts smaller values first.

Syntax

C 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.

From the programint readings[] = {INT_MAX, 7, INT_MIN, 7}
Resultsorted extremes and duplicates
lesson.c
#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;
}
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

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?

Given3 · 0 · 8 · 3
Worked result0 · 3 · 3 · 8