Arrange Numbers In Order

Hey, I've been trying to figure out a way to arrange 3 user-inputted numbers in order from greatest to least, but so far have been unable to do so. Is there a simple and efficient way to get this done?
Yes, use a 2x std::min call, a 2x std::max call, and then take the sum of the three numbers, but then subtract the minimum and maximum. You're left with the number that's neither the minimum or maximum -- the median. In general, use Median of medians for the middle element (you can simplify it a ton by knowing there's only 3 values instead of N values).

https://en.cppreference.com/w/cpp/algorithm/min
https://en.cppreference.com/w/cpp/algorithm/max
https://en.wikipedia.org/wiki/Median_of_medians (Generalized for N numbers)
https://stackoverflow.com/a/29242318/8690169 (Easy calculation for 3 numbers)

Or... lazy alternative:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Example program
#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int a = 5;
    int b = 3;
    int c = 4;
    
    std::vector<int> numbers {a, b, c};
    std::sort(numbers.begin(), numbers.end());
    std::cout << "min = " << numbers[0] << "\n"
              << "med = " << numbers[1] << "\n"
              << "max = " << numbers[2] << "\n";
}

:)

There's tons of ways to skin this cat.
Last edited on
try just doing it, inefficiently.

biggest = first;
if(second > biggest)
biggest = second;
if(third > biggest)
biggest = third;

and similar for smallest.
you can combine the statements to exploit things you know -- you know that if second > biggest then second is not smallest. If third > biggest, third is not smallest. The logic to exploit that is less intuitive than the naive approach and you have to be careful to get it right (that is why I said do the simple one and get that right first). All the extra twisting of the code saves like 1 comparison; its good to know you can do it and how to do it, but it isnt necessary here.
Last edited on
3 comparisons, right? ("inefficiently")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <random>

using namespace std;

int main()
{
    random_device rd;

    int times = 15;
    int big, mid, small;

    while (times--)
    {
        big = rd()%100 + 1;
        mid = rd()%100 + 1;
        small = rd()%100 + 1;

        cout << big << " " << mid << " " << small << '\n';

        // Fix small
        if (small>mid)
            swap(small,mid);
        
        if (small>big)
            swap(small,big);
        
        // Fix mid
        if (mid>big)
            swap(mid,big);    

        cout << big << " " << mid << " " << small << '\n' << '\n';
    }

    return 0;
}
Last edited on
Thanks for the help!
Topic archived. No new replies allowed.