冒泡排序

作者: 郭的妻 | 来源:发表于2018-05-23 08:27 被阅读5次
      <!DOCTYPE html>
         <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title>Document</title>
              </head>
        <body>
    <script>
    // 冒泡排序 =====   简洁版
        var arr = [23,35,56,87,34,324,234];
        var s = 0;
        var s1 = 0;
        for(var i=0; i<arr.length -1; i++){
            s++
            for(var j=0; j<arr.length - 1; j++){
                s1++
                if(arr[j] > arr[j + 1]){
                    var tem = arr[j]
                    arr[j] = arr[j+1]
                    arr[j+1] = tem
                };
            };
        };
        console.log(arr)
        console.log("外循环" + s)
        console.log("内循环" + s1)
        // 冒泡排序 =====   升极版
        var arr = [23,35,56,87,34,324,234];
        var s = 0;
        var s1 = 0;
        for(var i=0; i<arr.length -1; i++){
            s++
            // 注意这一条语句
            for(var j=0; j<arr.length - 1 -i; j++){
                s1++
                if(arr[j] > arr[j + 1]){
                    var tem = arr[j]
                    arr[j] = arr[j+1]
                    arr[j+1] = tem
                };
            };
        };
        console.log(arr)
        console.log("外循环" + s)
        console.log("内循环" + s1)
        
        // 冒泡排序 =====   终极版
        var arr = [23,35,56,87,34,324,234];
        var s = 0;
        var s1 = 0;
        for(var i=0; i<arr.length -1; i++){
            // 注意这一条语句
            var isNode = true
            s++
            for(var j=0; j<arr.length - 1 -i; j++){
                s1++
                if(arr[j] > arr[j + 1]){
                    isNode = false
                    var tem = arr[j]
                    arr[j] = arr[j+1]
                    arr[j+1] = tem
                };
            };
            // 注意这一条语句
            if(isNode){
                break;
            }
        };
        console.log(arr)
        console.log("外循环" + s)
        console.log("内循环" + s1)
    </script>
    </body>
    </html>

    相关文章

      网友评论

        本文标题:冒泡排序

        本文链接:https://www.haomeiwen.com/subject/pbmljftx.html