一、 js的sort()方法
console.log("------默认排序(ASCII字符排序)------");
var arr = [1,2,55,12,88];
arr.sort(); //ASCII字符代码从小到大排序
console.log(arr.toString());
console.log("------自定义函数排序------");
var arr1 = [1,2,55,12,88];
arr1.sort(function(a,b){ //自定义函数排序
var a1= parseInt(a);
var b1= parseInt(b);
if(a1<b1){
return -1;
}else if(a1>b1){
return 1;
}
return 0;
});
console.log(arr1.toString());
console.log("另外一种方法");
var arr = [10, 20, 1, 2];
arr.sort(function(a,b){
return a-b;
})
console.log(arr); //[1, 2, 10, 20]
console.log("------反转数组------");
var reArr = arr1.reverse(); //将数组中元素的顺序倒转
console.log(reArr.toString());
console.log("------按年龄正序排序------");
var arr2 = [];
arr2.push({date:"20130101",name:"lee",age:2});
arr2.push({date:"20130101",name:"wang",age:12});
arr2.push({date:"20130202",name:"huang",age:30});
arr2.push({date:"20130202",name:"keke1",age:14});
arr2.push({date:"20130202",name:"keke2",age:31});
arr2.push({date:"20130303",name:"keke3",age:56});
arr2.push({date:"20130303",name:"keke4",age:22});
arr2.push({date:"20130303",name:"keke5",age:32});
arr2.sort(function(a,b){
if(a.age<b.age){
return -1;
}else if(a.age>b.age){
return 1;
}
return 0;
});
for(var i=0;i<arr2.length;i++){
console.log(arr2[i].date + ", " + arr2[i].name + ", " + arr2[i].age);
}
console.log("------按date倒序,age正序排序------");
arr2.sort(function(a,b){
if(a.date<b.date){
return 1;
}else if(a.date>b.date){
return -1;
}else{
if(a.age<b.age){
return -1;
}else if(a.age>b.age){
return 1;
}
return 0;
}
});
for(var i=0;i<arr2.length;i++){
console.log(arr2[i].date + ", " + arr2[i].name + ", " + arr2[i].age);
}
二、 冒泡排序
var arr = [10, 20, 1, 2];
var t;
for(var i=0;i<arr.length;i++){
for(j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
console.log(arr); //[1, 2, 10, 20]
三、二维数组的排序(sort,冒泡)
1.二维数组使用sort()方法排序
var arr=[
["北京",80],
["上海",50],
["福州",10],
["广州",50],
["成都",70],
["西安",100],
];
arr.sort(function(a,b){
if(a[1]<b[1]){
return -1;
}
if(a[1]>b[1]){
return 1;
}
return 0;
})
console.log(arr); //["福州",10],["上海",50],["广州",50],["成都",70],["北京",80],["西安",100]
2.二位数组的冒泡排序
var arr=[["北京",80],["上海",50],["福州",10],["广州",50],["成都",70],["西安",100]];
var t;
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr.length-1;j++){
if(arr[j][1]>arr[j+1][1]){
t=arr[j][1];
arr[j][1]=arr[j+1][1];
arr[j+1][1]=t;
}
}
}
console.log(arr); //["福州",10],["上海",50],["广州",50],["成都",70],["北京",80],["西安",100]