排序随便写写
记录一下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);
网友评论