1、sort 排序法
var arr = [
{id:1,name:'小李',age:23},
{id:2,name:'小明',age:24},
{id:3,name:'小王',age:25},
{id:4,name:'小马',age:29},
]
var compare = function(obj1,obj2){
var val1 = obj1.age;
var val2 = obj2.age;
if(val1 < val2){
return 1;
}else if(val1 > val2){
return -1;
}else{
return 0;
}
}
var sortArr = arr.sort(compare);
console.log("数组对象排序:" ,sortArr);
2、冒泡排序
var list = [45,4,2,55,72,12,14,57,8,999,8,7,6,5,4,3,2,115,67,68,56,55,43,21];
function bubblingRank(arr) {
var temp ;
for (var i =0;i<arr.length;i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[j] < arr[j + 1]){
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
console.log("冒泡排序:",bubblingRank(list));
结果为
3、插入排序
var list= [0,4,2,6,7,8,2,14,57,8,99,0,45,32,121,1,3,2,115,67,68,56,55,43,21];
//插入排序
function insert(arr){
var s;
//升序
for (var i = 1; i < arr.length; i++) {
for (var j = i; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
s=arr[j];
arr[j]=arr[j-1];
arr[j-1]=s ;
//console.log(arr);//可以打印出来每一个改变的步骤
}
}
}
//降序
for (var i = 1; i < arr.length; i++) {
for (var j = i; j < 0; j--) {
if (arr[j] < arr[j - 1]) {
s=arr[j];
arr[j]=arr[j-1];
arr[j-1]=s ;
//console.log(arr);
}
}
}
return arr;
}
console.log("插入排序:",insert(list));