Write a JavaScript callback for the jQuery function
$(\"#sort\").click
. Allow the user to enter three numbers in any order. Output the numbers in ord
Some great jQuery answers here, I'll cover the comparisons part.
You don't need five comparisons, just three (or two if you're lucky). Compare a
and b
, and swap them if a > b
. Then compare c
and b
. If c > b
, you're done, otherwise compare c
and a
:
if (a > b)
x = a, a = b, b = x;
if (c < b)
if (c < a)
result = [c, a, b];
else
result = [a, c, b];
else
result = [a, b, c];
If all numbers are 32-bit positive ints, you can sort them without any comparisons at all:
min = function(a,b) { return b + ((a-b) & ((a-b)>>31)) }
max = function(a,b) { return a - ((a-b) & ((a-b)>>31)) }
x = min(a, min(b, c));
z = max(a, max(b, c));
y = (a + b + c) - (x + z);
result = [x, y, z];