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

[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript的更多相关文章

  1. Divide and Conquer.(Merge Sort) by sixleaves

    algo-C1-Introductionhtml, body {overflow-x: initial !important;}html { font-size: 14px; }body { marg ...

  2. Summary: Merge Sort of Array && 求逆序对

    常用算法(后面有inplace版本): package ArrayMergeSort; import java.util.Arrays; public class Solution { public ...

  3. geeksforgeeks@ Sorting Elements of an Array by Frequency (Sort)

    http://www.practice.geeksforgeeks.org/problem-page.php?pid=493 Sorting Elements of an Array by Frequ ...

  4. Array类的Sort()方法

    刚复习了Array类的sort()方法, 这里列举几个常用的,和大家一起分享. Array类实现了数组中元素的冒泡排序.Sort()方法要求数组中的元素实现IComparable接口.如System. ...

  5. [Algorithms] Sorting Algorithms (Insertion Sort, Bubble Sort, Merge Sort and Quicksort)

    Recently I systematicall review some sorting algorithms, including insertion sort, bubble sort, merg ...

  6. [Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript

    nsertion sort is another sorting algorithm that closely resembles how we might sort items in the phy ...

  7. Javascript判断object还是list/array的类型(包含javascript的数据类型研究)

    前提:先研究javascript中的变量有几种,参考: http://www.w3school.com.cn/js/js_datatypes.asp http://glzaction.iteye.co ...

  8. .NET中string[]数组和List<string>泛型的相互转换以及Array类的Sort()方法(转)

    从string[]转List<string>: " }; List<string> list = new List<string>(str); 从List ...

  9. js中的数组Array定义与sort方法使用示例

    Array的定义及sort方法使用示例 Array数组相当于java中的ArrayList  定义方法:  1:使用new Array(5  )创建数组 var ary = new Array(5): ...

随机推荐

  1. css去掉点击连接时所产生的虚线边框技巧兼容符合w3c标准的浏览器

    解决方法: 1.在css中加上outline:none; 代码如下: a.fontnav { text-align:left;color:#555; text-decoration:none; out ...

  2. 简易web服务器(npm)

    npm install -g http-server 以后可以在任何一个文件夹启动静态文件的访问通过http-server -a localhost -p 8000ctrl + c结束 http-se ...

  3. POJ1018 Communication System

      Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 26738   Accepted: 9546 Description We ...

  4. 汕头市队赛 SRM10 T1 贪心只能过样例

    贪心只能过样例 SRM 10 描述 给出n个数a[i](1<=a[i]<=n),问最多能把这些数分成几组,使得每个数a[i]所在的组至少有a[i]个数 输入格式 第一行一个整数n,接下来n ...

  5. 求LCA最近公共祖先的离线Tarjan算法_C++

    这个Tarjan算法是求LCA的算法,不是那个强连通图的 它是 离线 算法,时间复杂度是 O(m+n),m 是询问数,n 是节点数 它的优点是比在线算法好写很多 不过有些题目是强制在线的,此类离线算法 ...

  6. cannot load shared object file undefined symbol

    cannot load shared object file undefined symbol 场景: 共享库里引用了主程序一个符号,结构编译的时候没问题,运行时用 dlopen 打开共享库报上述错误 ...

  7. Linux内核实践之序列文件【转】

    转自:http://blog.csdn.net/bullbat/article/details/7407194 版权声明:本文为博主原创文章,未经博主允许不得转载. 作者:bullbat seq_fi ...

  8. VBA 学习

    Sub abc() Dim i Dim coloumn coloumn = For i = To Dim currentValue currentValue = Val(ReplaceChar(She ...

  9. 【原创】SQL Server Job邮件详细配置

    1 简介 SQL Server 代理具有发送电子邮件的功能.您可以配置 SQL Server 代理邮件,使其在出现下列情况时向预定义的操作员发送电子邮件: 警报触发时.可以配置警报,以针对所发生的特定 ...

  10. Laravel中ajax添加CsrfToken的方法

    //在模板文件的header头中添加 <meta name="_token" content="{{ csrf_token() }}"/> //aj ...