js計算三個數字的大小,按從小到大的順序打印


冒泡排序法

1)先比較a和b的大小,把最大值賦值給a
2)再比較b和c的大小,把最大值賦值給b
3)再比較a和b的大小,把最大值賦值給a

 function  size(a,b,c){
            var num,a,b,c;
           if(a>b){
            num=a;
            a=b;
            b=num
           }
           if(b>c){
            num=b;
            b=c;
            c=num
           }
           if(a>b){
            num=a;
            a=b;
            b=num
           }
           document.write(a+" "+b+" "+c)
        }
        size(8,2,3)

窮舉法

<body>
        <input type="text" name="" id="n1">
        <input type="text" name="" id="n2">
        <input type="text" name="" id="n3">
        <input type="button" value="排序" id="btn">
    </body>
    <script>
        var n1=document.getElementById("n1");
        var n2=document.getElementById("n2");
        var n3=document.getElementById("n3");
        var btn=document.getElementById("btn")
        btn.onclick=function(){
            var num1=n1.value;
            var num2=n2.value;
            var num3=n3.value
            size(num1,num2,num3)
        }
        function size(a,b,c){
            if(a>b&&a>c){
                if(b>c){
                console.log(a,b,c)
            }else{
                console.log(a,c,b)
            }
            }
            if(b>a&&b>c){
                if(a>c){
                console.log(b,a,c)
            }else{
                console.log(b,c,a)
            }
            }
            if(c>a&&c>b){
                if(a>b){
                console.log(c,a,b)
            }else{
                console.log(c,b,a)
            }
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM