[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): ...
随机推荐
- nutch2.3.1源码分析——InjectorJob
InjectorJob实现的功能是:从种子站点文件当中读取站点信息并且将这些站点的个数.url(url以 域名:协议/端口号/路径名 设为形式存储在数据库当中,为了提高读写速度)回写到Context类 ...
- Eclipse中使用Maven创建Web时错误
一.问题描述 使用Eclipse创建Maven项目时,报一下错误,不能创建成功. 二.问题原因 错误详细描述是说 Could not resolve archetype org.apache.mave ...
- jQuery遍历文档(重要)
什么是遍历? jQuery 遍历,意为"移动",用于根据其相对于其他元素的关系来"查找"(或选取)HTML 元素.以某项选择开始,并沿着这个选择移动,直到抵达您 ...
- Instruments Tutorial for iOS: How To Debug Memory Leaks
http://www.raywenderlich.com/2696/instruments-tutorial-for-ios-how-to-debug-memory-leaks Update 4/12 ...
- 链表各种操作及其实现方法(c实现)
链表是一种最简单的数据结构之一,经常会被面试官用来考察应聘者的基础扎不扎实,最近也到了求职季,所以我把自己对链表的一些理解写出来,希望能跟大家交流交流: 链表的概念其实挺简单,无非就是一个利用指针将数 ...
- linux的文件布局
/bin---权限为 rwxr-xr-x 所有者为root/root 用户bin最先进入的工作目录就是这里.这里放置的是执行目录,但是特殊在这里的命令可以被一般用户使用(root更能使用).例如 ca ...
- android的百度地图开发(一)
1,注册百度开发者账号 2,申请key ,注意开发版SH和发布版的SH 获取开发版SHA1: 输入命令:keytool -list -v -keystore debug.keystore,回车输入 ...
- Appium+python自动化6-Remote远程控制【转载】
前言 在第三篇启动app的时候有这样一行代码driver = webdriver.Remote('http://192.168.1.1:4723/wd/hub', desired_caps),很多小伙 ...
- HDU 2602.Bone Collector-动态规划0-1背包
Bone Collector Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)To ...
- CF985B Switches and Lamps【矩阵操作/枚举】
[链接]CF985B [题意]:给n盏灯,m个开关,每次按开关只能将灯从灯灭的状态转变为灯亮,问是否存在不按所有开关就将所有灯打开的方法. [分析]:有两种办法,一种代码复杂点,容易想到枚举去掉每一行 ...