JavaScript - 排序算法 - 归并排序

2020-10-22  本文已影响0人  ElricTang

特点:

原理:(分治法)

代码实现:(递归)

// 采用自上而下的递归方法
function mergeSort(arr) {  
    const len = arr.length;
    if (len < 2) return arr;
    const middle = Math.floor(len >> 1);
    const left = arr.slice(0, middle);
    const right = arr.slice(middle);

    return merge(mergeSort(left), mergeSort(right));
}
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;
}
上一篇下一篇

猜你喜欢

热点阅读