How to sort three numbers most simply in C++

1 Answer

0 votes
#include <iostream>

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

    Why this approach?
        • For exactly three values, the minimal number of comparisons is three.
        • Each comparison conditionally swaps two values.
        • No loops, no arrays, no std::sort — extremely lightweight.
        • Idiomatic: uses std::swap, which is clear and safe.

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

void sortThree(int &a, int &b, int &c) {
    if (a > c)
        std::swap(a, c);

    if (a > b)
        std::swap(a, b);

    if (b > c)
        std::swap(b, c);
}

int main() {
    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];

        sortThree(a, b, c);

        std::cout << "sorted("
                  << values[i][0] << ", "
                  << values[i][1] << ", "
                  << values[i][2] << ") = "
                  << a << ", " << b << ", " << c << "\n";
    }
}


/*
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
...