-1

Write a JavaScript callback for the jQuery function $("#sort").click. Allow the user to enter three numbers in any order. Output the numbers in order from lowest to highest.

$(document).ready(function() {
  $("#sort").click(function() {
    var a = Number($("#a").val());
    var b = Number($("#b").val());
    var c = Number($("#c").val());
    var message = "";
   if (b > c) {
     if ((b + c) > (a + c)) {
       message = c + " " + a + " " + b;
     } else {
       message = c + " " + b + " " + a;
     }
   } else {
     message = b + " " + a + " " + c;
   }
    if (b > a) {
      if ((a + b) > (a + c)) {
        message = a + " " + c + " " + b;
      } else {
        message = a + " " + b + " " + c;
      }
    } else {
      message = b + " " + c + " " + a;
    }
  $("#output").html(message)
  });
});

Would anyone mind looking at this code and saying what's wrong?

6
  • Sorry I forgot to add that you can only use five comparisons. Commented Oct 7, 2014 at 21:21
  • 2
    What majes you think that "it's wrong"? Commented Oct 7, 2014 at 21:24
  • 1
    given his constraints for only using five comparisons, this is probably a lesson of some kind Commented Oct 7, 2014 at 21:26
  • Is the output different than what you expect or why do you think that there is something wrong? We have a close reason for this kind of question, which reads "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself." Commented Oct 7, 2014 at 21:27
  • In your example, you're manually checking for every possible permutation, instead of letting the computer work for you. Why not just use Array.sort()? Commented Oct 7, 2014 at 21:32

5 Answers 5

2

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];
Sign up to request clarification or add additional context in comments.

Comments

0

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});

Comments

0

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.

2 Comments

Major spoiler alert: Array.sort()
Bergi: Whoops! Forgot about that. Updated.
0

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);
    });
});

Comments

-2

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>

17 Comments

Lacks explanation as well as correctness (not even taking the horrible code into account)
Will update answer with description at comments . If possible , can detail "correctness" ? Thanks
"All JS engines that someone tested with a specific example" is by no means a generic reason. In general, you cannot rely on this, and you should not - especially when answering a newbie question.
Apart from that, there's no reason to do msg = Object.keys(n).join(""); inside of the loop; and delete n is total rubbish.
The issue with delete is a) that you are using n in the next iteration of the loop b) that it doesn't work like that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.