排序算法之归并排序(merge sort)

  • A+
所属分类:typescript 算法
function merge(left: Array<number>, right: Array<number>): Array<number> {
    let res = []
    let l = 0
    let r = 0

    while (l < left.length && r < right.length) {
        if (left[l] < right[r]) {
            res.push(left[l++])
        } else {
            res.push(right[r++])
        }
    }

    return [...res, ...left.slice(l), ...right.slice(r)]
}

function sort(arr: Array<number>): Array<number> {
    if (arr.length < 2) return arr
    let pivot = ~~(arr.length/2)
    let left = arr.slice(0, pivot)
    let right = arr.slice(pivot)
    return merge(sort(left), sort(right))
}

export default sort
weinxin
我的微信
欢迎来撩!!
admin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: