美文网首页
merge sort: sort then merge

merge sort: sort then merge

作者: Time_Notes | 来源:发表于2020-07-11 04:16 被阅读0次

动画

https://luanpeng.blog.csdn.net/article/details/78056408

var merge=function (a,b) {

    let c = []

    let i=0;

    let j=0;

    while(i<a.length && j<b.length){

        a[i]<b[j]?c.push(a[i++]):c.push(b[j++])

    }

    if(i<a.length) c=c.concat(a.slice(i))

    if(j<b.length) c=c.concat(b.slice(j))

    return c;

}

var sort = function(arr) {

    if(arr.length<2) return arr;

    let mid = Math.floor(arr.length/2)

    let left = arr.slice(0,mid)

    let right = arr.slice(mid)

    return merge(sort(left),sort(right))

}

相关文章

网友评论

      本文标题:merge sort: sort then merge

      本文链接:https://www.haomeiwen.com/subject/qihoqktx.html