[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): ...
随机推荐
- Codeforces 934.B A Prosperous Lot
B. A Prosperous Lot time limit per test 1 second memory limit per test 256 megabytes input standard ...
- js获取url参数,操作url参数
function getParam(key) { var tmp = location.search; tmp = decodeURIComponent(tmp); var index = tmp.i ...
- NGINX: 优化 use 参数
转自:http://blog.sina.com.cn/s/blog_5eaf88f10100gkrq.html Nginx use参数分析对比 下图对比了poll select epoll和kqueu ...
- 分享一下我写的.net 2.0的orm类,实现mvc。可以用于webform等环境中,这是orm的原理部分。
using System;using System.Collections.Generic;using System.Configuration;using System.Data;using Sys ...
- webservice跨域文件,好多年前的东西,远程调用,js服务器端使用,可以远程调用
1.clientaccesspolicy.xml <?xml version="1.0" encoding="utf-8" ?> <acces ...
- C程序编译过程浅析【转】
转自:http://blog.csdn.net/koudaidai/article/details/8092647 前几天看了<程序员的自我修养——链接.装载与库>中的第二章“编译和链接” ...
- cat /proc/maps 进程内存映射【转】
转自:http://blog.csdn.net/fisher_jiang/article/details/5063852 proc/<PID>/maps查看进程的虚拟地址空间是如何使用的. ...
- Linux内核驱动之延时---内核超时处理【转】
转自:http://blog.chinaunix.net/uid-24219701-id-3288103.html 内核超时处理 jiffies 计数器 定时器中断由系统定时硬件以规律地间隔产生; 这 ...
- 右上角X灰化
CMenu* menu = this->GetSystemMenu(FALSE); menu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_GRA ...
- JavaScript 开发者的 10 款必备工具
JavaScript,一种所有主流浏览器都支持的语言,是开发基于浏览器的 Web 应用程序的主力,几乎每年都会受到来自众多开发人员的关注.自然地,框架和库的生态系统自然而然地围绕着 JavaScrip ...