function mergeSort(arr){
if(arr.length<2){
return arr
}
let middle = parseInt(arr.length/2)
let left = arr.slice(0,middle)
let right = arr.slice(middle)
function merge(left,right){
let result = []
while(left.length && right.length){
if(left[0]<=right[0]){
result.push(left.shift())
}else{
result.push(right.shift())
}
}
while(left.length){
result.push(left.shift())
}
while(right.length){
result.push(right.shift())
}
return result
}
return merge(mergeSort(left), mergeSort(right))
}
快速排序
var quickSort = function(arr) {
if (arr.length < 2) {
return arr
}
let middle = arr.splice(parseInt(arr.length / 2),1)[0]
var left = []
var right = []
for (var i = 0; i < arr.length; i++){
if (arr[i] < middle) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([middle], quickSort(right));
}
計數(shù)排序
function countingSort(array) {
var len = array.length,
B = [],
C = [],
min = max = array[0];
for (var i = 0; i < len; i++) {
min = min <= array[i] ? min : array[i];
max = max >= array[i] ? max : array[i];
C[array[i]] = C[array[i]] ? C[array[i]] + 1 : 1;
}
for (var j = min; j < max; j++) {
C[j + 1] = (C[j + 1] || 0) + (C[j] || 0);
}
for (var k = len - 1; k >= 0; k--) {
B[C[array[k]] - 1] = array[k];
C[array[k]]--;
}
return B;
}