Sorting algorithm in Javascript

后端 未结 5 560
情深已故
情深已故 2021-01-29 09:23

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

5条回答
  •  梦毁少年i
    2021-01-29 10:11

    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.

提交回复
热议问题