归并排序
原理
归并排序是一种分治算法。其思想是将原始数组切分成较小的数组,直到每个小数组只有一个位置,接着将小数组归并成较大的数组,直到最后只有一个排序完毕的数组。
function merge(left, right) {
let result = [],
i = 0,
j = 0;
while(i < left.length && j < right.length) {
if(left[i] < right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
while(i < left.length) {
result.push(left[i++]);
}
while(j < right.length) {
result.push(right[j++]);
}
return result;
}
function mergeSort(array) {
let mid, left, right;
if(array.length <= 1) {
return array;
}
mid = Math.floor(array.length / 2);
left = array.slice(0, mid);
right = array.slice(mid, array.length);
return merge(mergeSort(left), mergeSort(right));
}
let array = [1, 5, 2, 4, 3];
array = mergeSort(array);
console.log(array);