edit:
On odd change that someone is reading this, I’d like to add one last thing.
Assuming that the three values in question are already in memory and they are not changed, I’ve counted no less than 14 instructions to be able to achieve this feat.
I’s very much like this confirmed if anyone can.
[top edit end]
The problem is simple. I have three integer values and I need to find the largest and the smallest. By largest I mean not smallest or in between and vice versa.
As I was unable to find a “quality solution” online, I had to make my own attempt.
if(a > b) {
if(a > c) {
high = a;
if(b > c) {
low = c;
}
else {
low = b;
}
}
else {
if(b > c) {
high = b;
low = c;
}
else {
high = c;
low = b;
}
}
}
else if(a > c) {
if(b > c) {
high = b;
low = c;
}
else {
high = c;
low = b;
}
}
else {
low = a;
if(b > c) {
high = b;
}
else {
high = c;
}
}
Assuming I have not made any mistakes, this should solve the problem using three conditionals.
Assuming it works as intended, I’m rather pleased with my effort actually, however my intention was to find the most efficient algorithm, thus I ask you now what that is.
Best regards.
Edit:
I’ve reviewed the solutions proposed so far and they’re all nice.
My favorite so far.
if(a>b) {
max = a;
min = b;
}
else {
max = b;
min = a;
}
if(c>max)
max = c
else if(c< min)
min = c
2-3 sigments and 2-3 conditionals, if I’m not mistaken. That’s impressive.
small revision of the above, using ‘a’ as alias for ‘min’.
if(a>b) {
max = a;
a = b;
}
else {
max = b;
}
if(c>max)
max = c
else if(c< a)
a = c
If only there was an easy way to exchange variables… Well, the only thing I can think of is that could eliminate the need for ‘max’, at least in C and C derivatives, certainly wouldn’t be efficient, other than in terms of memory use, and I can affort to spend an extra 4 bytes. 😉
1 Answer