欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《js基础-排序》sort排序、冒泡排序、数组排序、正序、倒序

程序员文章站 2022-03-21 21:25:19
...
/*------------排序:-----------*/
       /*正序:*/
       var array = [7455,52,564,324,885,4632,1,5,73,4,8];
       array.sort(function(a,b){
           return a - b;
       });
       console.log(array);//输出[1, 4, 5, 8, 52, 73, 324, 564, 885, 4632, 7455]
       /*倒序:*/
       var array1 = [7455,52,564,324,885,4632,1,5,73,4,8];
       array1.sort(function(a,b){
           return b - a;
       });
       console.log(array1);//输出[7455, 4632, 885, 564, 324, 73, 52, 8, 5, 4, 1]

       var array2 = [{id:'2kh45l3mm4n5l2l4h2',num:8},{id:'3kh45l3mm4n5l2l4h2',num:98},{id:'dfj3l4h2j4ssio4',num:7}
       ,{id:'ll43jro4hretlir94',num:998},{id:'lwei234j2l34idjdrir8el',num:3}];
       array2.sort(function(a,b){
           return a.num - b.num
       });
       console.log(array2);
      //输出:
       // 0: {id: "lwei234j2l34idjdrir8el", num: 3}
       // 1: {id: "dfj3l4h2j4ssio4", num: 7}
       // 2: {id: "2kh45l3mm4n5l2l4h2", num: 8}
       // 3: {id: "3kh45l3mm4n5l2l4h2", num: 98}
       // 4: {id: "ll43jro4hretlir94", num: 998}

     var array3 = [{id:'2kh45l3mm4n5l2l4h2',num:8,sum:874},{id:'3kh45l3mm4n5l2l4h2',num:98,sum:534},{id:'dfj3l4h2j4ssio4',num:7,sum:21}
         ,{id:'ll43jro4hretlir94',num:998,sum:3},{id:'lwei234j2l34idjdrir8el',num:3,sum:76}];
        array3.sort(function(a,b){
            if(a.num === b.num){//如果id相同,按照age的降序
                return b.sum - a.sum
            }else{
                return a.num - b.num
            }
        });
        console.log(array3);
        //输出(num列递增):
     //0: {id: "lwei234j2l34idjdrir8el", num: 3, sum: 76}
     //1: {id: "dfj3l4h2j4ssio4", num: 7, sum: 21}
     //2: {id: "2kh45l3mm4n5l2l4h2", num: 8, sum: 874}
    // 3: {id: "3kh45l3mm4n5l2l4h2", num: 98, sum: 534}
     //4: {id: "ll43jro4hretlir94", num: 998, sum: 3}

    /* 冒泡排序-正序:*/
    function f(array) {
        for (i = 0; i < array.length; i++) {
            for (t = 0; t < array.length - i - 1; t++) {
                if (array[t] > array[t + 1]) {
                    var num = array[t];
                    array[t] = array[t + 1];
                    array[t + 1] = num;
                }
            }
        }
        return array;
    }
    console.log(f([5, 3, 78, 32, 95, 32, 56, 2]));//[2, 3, 5, 32, 32, 56, 78, 95]
    /* 冒泡排序倒序:*/
    console.log(f([5, 3, 78, 32, 95, 32, 56, 2]).reverse());//[95, 78, 56, 32, 32, 5, 3, 2]
    /*以下可略:*/
    /*不带参数的排序--任意排序:*/
       var array4 = ['张三','李四','王五'];
       console.log(array4.sort());//输出["张三", "李四", "王五"]

       var array5 = [7455,52,564,324,885,4632,1,5,73,4,8];
       console.log(array5.sort());//输出:[1, 324, 4, 4632, 5, 52, 564, 73, 7455, 8, 885]