1
\$\begingroup\$

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?

\$\endgroup\$
  • 4
    \$\begingroup\$ Is this for Java or JavaScript? They're two different languages. \$\endgroup\$ – Jamal Dec 27 '13 at 8:02
  • 3
    \$\begingroup\$ Currently I need this for Javascript, but, the code for Java is the same. \$\endgroup\$ – Erel Segal-Halevi Dec 27 '13 at 9:38
  • 5
    \$\begingroup\$ 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. \$\endgroup\$ – 200_success Dec 27 '13 at 10:06
  • 2
    \$\begingroup\$ Micro-optimizations like these have little effect. I suggest you go for the 2-liner if you really want it short. \$\endgroup\$ – Joseph Dec 27 '13 at 10:08
  • \$\begingroup\$ @200_success thanks, this is a good idea, I will do this one piece at a time.. \$\endgroup\$ – Erel Segal-Halevi Dec 27 '13 at 11:34
3
\$\begingroup\$
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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.