# min and max simultaneously

I have two numbers: a and b. I want to put the smaller of them in one variable, and the larger in another variable (if they are equal, then any of them can be in any of the variables). Currently my code (in Javascript / Java) takes 7 lines:

if (a<=b) {
small = a;
large = b;
} else {
small = b;
large = a;
}


I could also use the Math.max and Math.min functions:

small = Math.min(a,b);
large = Math.max(a,b);


This takes only 2 lines but it is wasteful because the test of which one is larger will be done twice - once in Math.min and once in Math.max.

Is there a shorter / more elegant way to do this?

• Is this for Java or JavaScript? They're two different languages. – Jamal Dec 27 '13 at 8:02
• Currently I need this for Javascript, but, the code for Java is the same. – Erel Segal-Halevi Dec 27 '13 at 9:38
• If you are seriously concerned about the performance penalty of doing two comparisons here, perhaps you should post a bigger chunk of code so we can inspect your whole algorithm for inefficiencies. – 200_success Dec 27 '13 at 10:06
• Micro-optimizations like these have little effect. I suggest you go for the 2-liner if you really want it short. – Joseph Dec 27 '13 at 10:08
• @200_success thanks, this is a good idea, I will do this one piece at a time.. – Erel Segal-Halevi Dec 27 '13 at 11:34

int t = a + b;
a = a > b ?  t - a : a;
b = t - a;
// a is the small one


Or

small = a;
large = b;
if (a>b) {
small = b;
large = a;
}


But I think it will be shorter in Python:

if a > b:
a, b = b, a