-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?

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • Sorry I forgot to add that you can only use five comparisons. – carenekl Oct 07 '14 at 21:21
  • 2
    What majes you think that "it's wrong"? – David says reinstate Monica Oct 07 '14 at 21:24
  • 1
    given his constraints for only using five comparisons, this is probably a lesson of some kind – AlexanderBrevig Oct 07 '14 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."* – Felix Kling Oct 07 '14 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()? – thykka Oct 07 '14 at 21:32
  • Why are you comparing sums to each other, instead of just the numbers? – Bergi Oct 07 '14 at 21:42

5 Answers5

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];
georg
  • 195,833
  • 46
  • 263
  • 351
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.

suavidas
  • 85
  • 3
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});
Ningappa
  • 51
  • 1
  • 2
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);
    });
});
Jonathan
  • 7,345
  • 3
  • 31
  • 63
-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>
guest271314
  • 1
  • 10
  • 82
  • 156
  • 1
    Lacks explanation as well as correctness (not even taking the horrible code into account) – Bergi Oct 07 '14 at 22:19
  • Will update answer with description at comments . If possible , can detail "correctness" ? Thanks – guest271314 Oct 07 '14 at 22:20
  • Well, if you can *reason* that and why it works as expected, it is correct. I bet you cannot. – Bergi Oct 07 '14 at 22:21
  • @Bergi Not certain about meaning of "_reason_" ? Description of `object` key sorting in js ? Please illuminate errors at piece / comment description ? Thanks – guest271314 Oct 07 '14 at 22:27
  • Yes, [reason](https://en.wikipedia.org/wiki/Reason#Computer_science). What is "object key sorting"? – Bergi Oct 07 '14 at 22:31
  • @Bergi Interesting :) See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Examples (third example) , console at http://jsfiddle.net/guest271314/6jmv526a/5/ – guest271314 Oct 07 '14 at 22:43
  • I'm not looking for "examples". There is [no defined](http://stackoverflow.com/a/17101063/1048572) [order of keys](http://stackoverflow.com/a/9658712/1048572) (except for "always the same"). – Bergi Oct 07 '14 at 23:06
  • Not exactly certain what "looking for" ? jsfiddle at previous comment , perhaps , visually demonstrates the "re-ordering" of the resultant array returned by `Object.keys()` . The array initially begins with `[2, 7]` , then gets "sorted" to `[1, 2, 7]` when the value `1` gets added as a property of `n` . At first link: _"All JS engines that I tested on return numerical order: "1", "2", "10""_ :) – guest271314 Oct 07 '14 at 23:30
  • 1
    "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. – Bergi Oct 07 '14 at 23:36
  • 1
    Apart from that, there's no reason to do `msg = Object.keys(n).join("");` inside of the loop; and `delete n` is total rubbish. – Bergi Oct 07 '14 at 23:37
  • @Bergi If possible , can create piece / case where numerical order would _not_ be returned ? given _type_ of input ? Which specific engines would return a _non_-numerical order ? Fair enough at `.join()` . What is issue with `delete` ? , not needed for any further processing at that point , why not call `delete` ? – guest271314 Oct 07 '14 at 23:43
  • @Bergi If answer is _not_ helpful , should remove ? Thanks – guest271314 Oct 07 '14 at 23:51
  • It's *your* piece that might not give numerical order - e.g. in [these browsers](https://code.google.com/p/v8/issues/detail?id=164#c8). – Bergi Oct 07 '14 at 23:58
  • 1
    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](http://perfectionkills.com/understanding-delete/). – Bergi Oct 07 '14 at 23:59
  • @Bergi Withdrawn (although your comments _are_ helpful as to the question / `Object.keys()` . Should keep post up for your comments ?) . Thanks ! – guest271314 Oct 08 '14 at 00:06
  • @Bergi See updated post. Tried with numbers 0-9 . Could add 10-n numbers to `n` for numbers greater than 10 . Thanks – guest271314 Oct 08 '14 at 23:14
  • Um, that's *interesting*. I've never seen anybody use `[].slice.call("0123456789")` - common is `"0123456789".split('')`. The algorithm you use for sorting is creative, but unfortunately slow and works only for a finite set of numbers. It reminds me of radix sort somehow, though. – Bergi Oct 08 '14 at 23:21