冒泡排序
function mySort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
快速排序
function sort(arr) {
if(arr.length<=1){
return arr;
}
var middle = arr[0];
var left = [];
var right = [];
for(var i =1;i<arr.length;i++){
var value = arr[i];
if (value<middle){
left.push(value)
}else {
right.push(value)
}
}
return sort(left).concat(middle,sort(right))
}
归并排序
function merge(left, right) {
var result = [];
while(left.length > 0 && right.length > 0) {
if(left[0] < right[0]) {
result.push(left.shift());
}
else {
result.push(right.shift());
}
}
/* 当左右数组长度不等.将比较完后剩下的数组项链接起来即可 */
return result.concat(left).concat(right);
}
function mergeSort(arr){
if(arr.length==1) {return arr};
var mid=Math.floor(arr.length/2);
var left_arr=arr.slice(0,mid),right_arr=arr.slice(mid);
return merge(mergeSort(left_arr),mergeSort(right_arr));
}
网友评论