[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:
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的更多相关文章
- Divide and Conquer.(Merge Sort) by sixleaves
algo-C1-Introductionhtml, body {overflow-x: initial !important;}html { font-size: 14px; }body { marg ...
- Summary: Merge Sort of Array && 求逆序对
常用算法(后面有inplace版本): package ArrayMergeSort; import java.util.Arrays; public class Solution { public ...
- 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 ...
- Array类的Sort()方法
刚复习了Array类的sort()方法, 这里列举几个常用的,和大家一起分享. Array类实现了数组中元素的冒泡排序.Sort()方法要求数组中的元素实现IComparable接口.如System. ...
- [Algorithms] Sorting Algorithms (Insertion Sort, Bubble Sort, Merge Sort and Quicksort)
Recently I systematicall review some sorting algorithms, including insertion sort, bubble sort, merg ...
- [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 ...
- Javascript判断object还是list/array的类型(包含javascript的数据类型研究)
前提:先研究javascript中的变量有几种,参考: http://www.w3school.com.cn/js/js_datatypes.asp http://glzaction.iteye.co ...
- .NET中string[]数组和List<string>泛型的相互转换以及Array类的Sort()方法(转)
从string[]转List<string>: " }; List<string> list = new List<string>(str); 从List ...
- js中的数组Array定义与sort方法使用示例
Array的定义及sort方法使用示例 Array数组相当于java中的ArrayList 定义方法: 1:使用new Array(5 )创建数组 var ary = new Array(5): ...
随机推荐
- mac 安装 nodeJs&npm 配置
前言:继续安装 nodeJS 下载安装:直接去官网,点击安装即可. 命令式安装: 1. 安装 homebrew 2. 安装 nodeJS,使用命令:brew install node 3. 测试 no ...
- 《Linux命令、编辑器与shell编程》第三版 学习笔记---000
Linux概述 1.具有内核编程接口 2.支持多用户(同时) 3.支持多任务 4.支持安全的分层文件系统 a.标准 b.链接 c.权限 5.shell(命令解释器和编程语言) a.文件名生成(通配符和 ...
- 读取文本文件时<U+FEFF> 导致的奇怪问题
项目中经常会从一些文本文件中读取数据进行业务处理,最近遇到一个问题,另外一个部门提供一个txt文本给我们进行业务处理,当我们使用字符流读取文本之后,处理时,发现第一行数据无法匹配,其他数据可以正常处理 ...
- log4j2配置文件动态指定日志文件名称
按照习惯性思维,log4j2中xml中取系统属性应该和log4j一样,但是结果却并不是我们想的这样,存在一定的差别,log4j中的配置可参考 log4j配置文件动态指定日志文件名称 . 现在就来看看到 ...
- qt include无法自动补齐
原因一: 检查cmake有没有include_directories 原因二: CmakeList.txt放错位置 原因三: 没有用qt new file来创建头文件
- MVC如何在路由器(RouteConfig)定义后缀.html
一.配置文件web.config添加一下设置 <system.webServer> <modules runAllManagedModulesForAllRequests=" ...
- 设计模式原则总结--读《大话设计模式》有感 <转>
读了<大话设计模式>,摘录该书中讲到的设计模式几大原则,供日后使用. 一.单一职责原则 就一个类而言,应该仅有一个引起它变化的原因.如果一个类承担的职责过多,就等于把这些职责耦合在一起,一 ...
- 在libGDX中使用Spine骨骼动画
首先,github是个宝库,实践流的读者可以直接看例子进行学习 1.这是Spine官方给出的例子 https://github.com/EsotericSoftware/spine-superspin ...
- Http与RPC通信协议的比较
OSI网络结构的七层模型 各层的具体描述如下: 第七层:应用层 定义了用于在网络中进行通信和数据传输的接口 - 用户程式:提供标准服务,比如虚拟终端.文件以及任务的传输 和处理: 第六层:表 ...
- UVA 437 巴比伦塔 【DAG上DP/LIS变形】
[链接]:https://cn.vjudge.net/problem/UVA-437 [题意]:给你n个立方体,让你以长宽为底,一个个搭起来(下面的立方体的长和宽必须大于上面的长和宽)求能得到的最长高 ...