How to sort three numbers most simply in C

1 Answer

0 votes
#include <stdio.h>

/*
    sort_three(a, b, c)
    -------------------
    Sorts three integers in ascending order using the simplest correct method.

    Why this algorithm?
        • Sorting exactly three numbers can be done with only three comparisons.
        • Each comparison conditionally swaps two values.
        • No loops, no arrays, no dynamic memory — extremely lightweight.
        • Idiomatic C: uses a tiny helper swap function for clarity.

    Algorithm:
        1. Ensure a <= c
        2. Ensure a <= b
        3. Ensure b <= c
    After these three steps, the values are guaranteed to be sorted.
*/

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

void sort_three(int *a, int *b, int *c) {
    if (*a > *c)
        swap(a, c);

    if (*a > *b)
        swap(a, b);

    if (*b > *c)
        swap(b, c);
}

int main(void) {
    int values[][3] = {
        {3, 1, 2},
        {10, 5, 7},
        {100, 50, 75},
        {9, 9, 1},
        {42, 0, -5},
        {8, 4, 4}
    };

    int count = sizeof(values) / sizeof(values[0]);

    for (int i = 0; i < count; i++) {
        int a = values[i][0];
        int b = values[i][1];
        int c = values[i][2];

        sort_three(&a, &b, &c);

        printf("sorted(%d, %d, %d) = %d, %d, %d\n",
               values[i][0], values[i][1], values[i][2],
               a, b, c);
    }

    return 0;
}


/*
run:

sorted(3, 1, 2) = 1, 2, 3
sorted(10, 5, 7) = 5, 7, 10
sorted(100, 50, 75) = 50, 75, 100
sorted(9, 9, 1) = 1, 9, 9
sorted(42, 0, -5) = -5, 0, 42
sorted(8, 4, 4) = 4, 4, 8

*/

 



answered Jul 22 by avibootz
...