sort //排序 引用同一个地址
var arr = [3, 7, 2, 9, 1, 0, 6, 5, 4, 4, 12, 11];
var arr1=arr.sort();
console.log(arr,arr1,arr==arr1);
arr.sort(function(a,b){
return a-b;
});
arr.sort(function(a,b){
return b-a;
});
var arr=["a","c","b","d","e","ab","bc","def","aaa","efg"];
arr.sort(function(a,b){
return a.charCodeAt(0)-b.charCodeAt(0);
});
//对象型数组某个属性排序
var arr=[
{id:1001,name:"苹果IphoneX",price:6900,num:2,info:"最新的苹果手机"},
{id:1002,name:"小米10",price:3900,num:3,info:"最新的小米手机"},
{id:1003,name:"华为meta10",price:8900,num:4,info:"最新的华为手机"},
{id:1004,name:"锤子手机",price:1900,num:1,info:"最新的锤子手机"},
{id:1005,name:"三星手机",price:4900,num:2,info:"最新的三星手机"},
{id:1006,name:"vivo手机",price:2900,num:4,info:"最新的vivo手机"},
{id:1007,name:"魅族手机",price:1900,num:5,info:"最新的魅族手机"},
];
arr.sort(function(a,b){
return a.price-b.price;
});
console.log(arr);
//排序算法
//冒泡排序
function sort(arr){
var len=arr.length-1;
while(len>0){
for(var i=0;i<arr.length-1;i++){
if(arr[i]>arr[i+1]){
var temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
len--;
}
}
//选择排序
function selectionSort(arr){
var len=arr.length;
var minIndex,temp;
for(var i=0;i<len-1;i++){
minIndex=i;
for(var j=i+1;j<len;j++){
if(arr[j]<arr[minIndex]){
minIndex=j;//将最小数的索引保存
}
}
temp=arr[i];
arr[i]=arr[minIndex];
arr[minIndex]=temp;
}
return arr;
}
//快速排序
function quickSort(arr){
if(arr.length<=1){
return arr;
}
var pivotIndex=parseInt(arr.length/2);
var pivot=arr.splice(pivotIndex,1)[0];
var left=[];
var right=[];
for(var i=0;i<arr.length;i++){
if(arr[i]<pivot){
left.push(arr[i]);
} else{
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot],quickSort(right));
}