//冒泡排序
function bubbleSort(arr){
for(var i = 0; i < arr.length-1; i++){
for(var j = 0; j < arr.length-i-1; j++){
if(arr[j] > arr[j+1]){
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort([6,1,2,4,3,5])); //[1,2,3,4,5,6]
//选择排序
function selectSort(arr){
var min,temp;
for(var i = 0; i < arr.length-1; i++){
min = i;
for(var j = i+1; j < arr.length; j++){
if(arr[j] < arr[min]){
min = j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr;
}
console.log(selectSort([6,2,1,3,4,5])); //[1,2,3,4,5,6]
//快速排序
function quickSort(arr){
if(arr.length < 2 ){return arr}
var left = [],right = [];
var mid = arr.splice(Math.floor(arr.length/2),1);
for(var i = 0; i < arr.length; i++){
if(arr[i] < mid){
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
return quickSort(left).concat(mid,quickSort(right))
}
console.log(quickSort([6,2,3,1,5,4])); //[1,2,3,4,5,6]
//插入排序
function insertSort(arr){
var len = arr.length;
for(var i = 1; i < len; i++){
var key = arr[i];
var j = i - 1;
while(j >= 0 && arr[j] > key){
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}
console.log(insertSort([5,4,2,3,1,6])); //[1,2,3,4,5,6]
js排序的几种方法
最新推荐文章于 2024-09-29 09:51:12 发布