// 以下 JavaScript 版本的实现利用了基础库 Array 的特有 API
// 并未考虑达到到最优的空间和时间,仅为了体现核心思想
function mergeSortTopDown(arr) {
function core(arr1, arr2) {
const rest = [];
while (arr1.length && arr2.length) {
rest.push(arr1[0] <= arr2[0] ? arr1.shift() : arr2.shift());
}
return rest.concat(arr1.concat(arr2));
}
const len = arr.length;
if (len < 2) {
return arr;
}
let mid = parseInt(len / 2);
return core(mergeSortTopDown(arr.slice(0, mid)), mergeSortTopDown(arr.slice(mid)));
}
function mergeSort(arr) {
const len = arr.length;
if(arr.length < 2){
return;
}
for (let step = 1; step < len; step *= 2) {
for (let i = 0; i < len; i = i + 2 * step) {
mergeArrays(
arr,
i,
Math.min(i + step, len),
Math.min(i + 2 * step, len)
);
};
}
//对左右序列进行排序
function mergeArrays(arr, left, right, end) {
let n = left,
m = right;
const currentSort = [];
for (let j = left; j < end; j++) {
if ( n < right && ( m >= end || arr[n] < arr[m] )) {
currentSort.push(arr[n]);
n++;
} else {
currentSort.push(arr[m]);
m++;
}
}
//
currentSort.forEach(function(item, index) {
arr[left + index] = item;
});
}
return arr;
}