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
Try
$("#sort").on("click", function (e) {
var vals = $.map($("#a, #b, #c"), function (v, k) {
return Number(v.value)
})
, min = null
, msg = "";
do {
min = Math.min.apply(Math, vals);
msg += min;
vals.splice($.inArray(min, vals), 1)
} while (vals.length > 0);
$("output").html(msg)
});
$("#sort").on("click", function (e) {
var vals = $.map($("#a, #b, #c"), function (v, k) {
return Number(v.value)
})
, min = null
, msg = "";
do {
min = Math.min.apply(Math, vals);
msg += min;
vals.splice($.inArray(min, vals), 1)
} while (vals.length > 0);
$("output").html(msg)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="a" type="text" value="2" />
<input id="b" type="text" value="7" />
<input id="c" type="text" value="1" />
<button id="sort">click</button>
<br />
<output></output>
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];
This is also right, But Better you put all values into an array.
Get All element value and push value into an array,
Use array.sort();;
to Sort numbers (numerically and ascending):
arrayname.sort(function(a, b){return a-b});
to Sort numbers (numerically and descending):
arrayname.sort(function(a, b){return b-a});
The biggest problem with the code is that it isn't well organized. Instead of using nested if statements to manually check every combination of values, try using the tools & methods that are already available to you.
To sort the values, you can put them in an array and call sort() on it.
//Function to compare numbers
function compareNumbers(a, b)
{
return a - b;
}
var a = Number($("#a").val());
var b = Number($("#b").val());
var c = Number($("#c").val());
//let's say a = 2, b = 3, c = 1
var arr = [a,b,c];
//The array arr is now [2,3,1]
arr.sort(compareNumbers);
//The array arr is now [1,2,3]
Now you can set the message by grabbing elements from arr in order.
Here's another (short) solution:
$(document).ready(function () {
$("#sort").click(function () {
var msg = [$("#a").val(), $("#b").val(), $("#c").val()].sort(
function (a, b) {
return a - b;
});
alert(msg);
});
});