美文网首页
js排序-随便写写

js排序-随便写写

作者: V_陈宇 | 来源:发表于2018-09-12 17:13 被阅读0次

    排序随便写写

    记录一下js排序
    插入排序

    //普通插入排序
      var ars = [15, 12, 18, 20, 1];
                var s = "";
                for(var i = 1; i < ars.length; i++) {
                    for(var j = i; j > 0; j--) {
                        if(ars[j] < ars[j - 1]) {
                            s = ars[j];
                            ars[j] = ars[j - 1];
                            ars[j - 1] = s;
                        }
                    }
                }
                console.log(ars);
    // list 插入排序
                var arList = [{
                        name: "1",
                        sort: 1,
                    },
                    {
                        name: "15",
                        sort: 15,
                    }, {
                        name: "2",
                        sort: 2,
                    }, {
                        name: "20",
                        sort: 20,
                    }
                ];
                var s = "";
                for(var i = 1; i < arList.length; i++) {
                    for(var j = i; j > 0; j--) {
                        if(arList[j].sort > arList[j - 1].sort) {
                            s = arList[j];
                            arList[j] = arList[j - 1];
                            arList[j - 1] = s;
                        }
                    }
                }
                console.log(arList);
    

    冒泡排序

    // 冒泡排序
                var moars = [20, 15, 2, 3, 50];
                var s = "";
                for(var i = 0; i < moars.length; i++) {
                    for(var j = 0; j < moars.length; j++) {
                        if(moars[j] > moars[j + 1]) {
                            s = moars[j];
                            moars[j] = moars[j + 1];
                            moars[j + 1] = s;
                        }
                    }
                }
                console.log(moars);
    

    相关文章

      网友评论

          本文标题:js排序-随便写写

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