[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript

Merge sort is a recursive sorting algorithm. If you don't understand recursion, I recommend finding a resource to learn it. In brief, recursion is the act of a function calling itself. Thus, merge sort is accomplished by the algorithm calling itself to provide a solution.

Merge sort divides the given array into two halves, a left half and a right half. We call merge sort on these sub-arrays. We continue to split our sub-arrays until we get arrays whose length is less than two. We then begin to stitch our small arrays back together, sorting them on the way up.

This is an efficient algorithm because we start by sorting very small arrays. By the time we reach our larger ones, they are already mostly sorted, saving us the need for expensive loops. To create our algorithm, we'll actually need two functions, our mergeSort function and a merge function that does the combining and sorting of our sub-arrays.

 

Utilize Javascript LIFO (last in first our queue stack to do the traverse)

For example:

[10, 5, 6, 3, 2, 8, 9, 4, 7, 1]
left [ 10 ] right [ 5 ] reuslts [ 5, 10 ]
left [ 3 ] right [ 2 ] reuslts [ 2, 3 ]
left [ 6 ] right [ 2, 3 ] reuslts [ 2, 3, 6 ]
left [ 5, 10 ] right [ 2, 3, 6 ] reuslts [ 2, 3, 5, 6, 10 ]
 
left [ 8 ] right [ 9 ]reuslts [ 8, 9 ]
left [ 7 ] right [ 1 ] reuslts [ 1, 7 ]
left [ 4 ] right [ 1, 7 ] reuslts [ 1, 4, 7 ]
left [ 8, 9 ] right [ 1, 4, 7 ] reuslts [ 1, 4, 7, 8, 9 ]

left [ 2, 3, 5, 6, 10 ] right [ 1, 4, 7, 8, 9 ] reuslts [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

 

复制代码
function mergeSort (array) {
    // if array is length less than two items, no need to sort
    if ( array.length < 2 ) {
        return array;
    }

    // find the middle point of the array to split it into two
    const middle = Math.floor(array.length / 2);
    const left = array.slice(0, middle);
    const right = array.slice(middle);

    return merge(
        mergeSort(left),
        mergeSort(right)
    )
}

function merge(left, right) {
    let sorted = [];
    console.log('left', left)
    console.log('right', right)
    while (left.length && right.length) {
        if (left[0] < right[0]) {
            sorted.push(left.shift())
        } else {
            sorted.push(right.shift())
        }
    }


    const reuslts = [...sorted, ...left, ...right];

    console.log('reuslts', reuslts)
    return reuslts;
}

let numbers = [10, 5, 6, 3, 2, 8, 9, 4, 7, 1]

mergeSort(numbers)

exports.mergeSort = mergeSort
复制代码

 

     

 

posted @   Zhentiw  阅读(253)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-12-22 [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
2017-12-22 [Recompose] Stream Props to React Children with RxJS
2017-12-22 [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component
2017-12-22 [Recompose] Handle React Events as Streams with RxJS and Recompose
2017-12-22 [Recompose] Stream a React Component from an Ajax Request with RxJS
2017-12-22 [Recompose] Pass a React Prop to a Stream in RxJS
2017-12-22 [Recompose] Configure Recompose to Build React Components from RxJS Streams
点击右上角即可分享
微信分享提示