[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): ...
随机推荐
- [LeetCode169]Majority Element
Majority Element Total Accepted: 58500 Total Submissions: 163658My Submissions Question Solution Gi ...
- linux和shell关系
坚持知识分享,该文章由Alopex编著, 转载请注明源地址: http://www.cnblogs.com/alopex/ 索引: 什么是shell shell的分类 shell脚本的执行方式 ...
- keystone总结
1. Keystone(OpenStack Identity Service)是OpenStack框架中,负责身份验证.服务规则和服务令牌的功能, 它实现了OpenStack的Identity API ...
- 【IDEA】使用intellij的idea集成开发工具中的git插件
注意:这里并没有介绍git客户端的安装,如果要安装客户端,大家可以参考如下的链接: http://www.runoob.com/git/git-install-setup.html 1.在使用这个id ...
- 放棋游戏(NOIP模拟赛)(DP)
没有原题... 囧.. [问题描述] 游戏规则是这样,有n(1<=n<=100)行格子,第一行由n个格子,第二行有n-1个格子,第三行由n-2个格子,……以此类推,第n行有1个格子.要求再 ...
- java基础练习 16
public class Sixtheen { /*利用递归方法求5!.*/ public static void main(String[] args){ System.out.println(&q ...
- hdu 5101(思路题)
Select Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Subm ...
- aliyun
阿里云启动不了网站 1 将网站的目录属性-安全中加入IUSER_计算机名字的访问权限 和 加入NER SERVICE的访问权限 2 IIS打开网站属性--目录--执行权限改为顺脚本 3 ...
- Codeforces Round #321 (Div. 2) A. Kefa and First Steps【暴力/dp/最长不递减子序列】
A. Kefa and First Steps time limit per test 2 seconds memory limit per test 256 megabytes input stan ...
- oracle Update a table with data from another table
UPDATE table1 t1 SET (name, desc) = (SELECT t2.name, t2.desc FROM table2 t2 WHERE t1.id = t2.id) WHE ...