一、用sort()方法进行数组排序
var arr1 = [20, 80, 54, 78, 8, 67, 27];
function my(a,b){
return a-b;
}
console.log(arr1.sort(my));//8,20,27,54,67,78,80
二、冒泡排序
var arr1 = [20, 80, 54, 78, 8, 67, 27];
function mys(arr1){
for(var i=0;i<arr1.length-1;i++){
for(var j=0;j<arr1.length-1-i;j++)
{
if(arr1[j]>=arr1[j+1]){
var temp=arr1[j+1];
arr1[j+1]=arr1[j];
arr1[j]=temp;
}
};
};
return arr1;//返回到数组
};
console.log(mys(arr1));//8,20,27,54,67,78,80
三、选择排序
var arr1 = [20, 80, 54, 78, 8, 67, 27];
function my(arr1) {
for (var i = 0; i < arr1.length - 1; i++) {
for (var j = i + 1; j < arr1.length; j++) {
if (arr1[i] > arr1[j]) {
var temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
};
};
};
return arr1;//返回到数组
};
console.log(my(arr1));//8,20,27,54,67,78,80