Last active
August 12, 2018 15:18
-
-
Save hackerrdave/14e542e89fdeee5fae6ffac1b1ea3a3f to your computer and use it in GitHub Desktop.
Algorithms | Merge Sort | JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Merge Sort Algorithm implemented in JavaScript | |
// By @hackerrdave | |
function mergeSort(arr) { | |
if (arr.length < 2) { | |
return arr; | |
} | |
let midpoint = Math.floor(arr.length / 2); | |
let leftHalf = arr.slice(0, midpoint); //slice an array of left-half items | |
let rightHalf = arr.slice(midpoint); //slice an array of right-half items | |
//recurse into each half until arrays are 1 item each | |
//then merge() the sorted arrays on each layer of the stack | |
return merge(mergeSort(leftHalf), mergeSort(rightHalf)); | |
} | |
//first time this merge() gets called, the arr's are both 1 element long | |
//on each layer of the stack the arrs will be doubled and always be sorted | |
function merge(arrA, arrB) { | |
let a = 0; | |
let b = 0; | |
let result = []; | |
while (a < arrA.length && b < arrB.length) { | |
if (arrA[a] < arrB[b]) { | |
result.push(arrA[a]); | |
a++; | |
} else { | |
result.push(arrB[b]); | |
b++; | |
} | |
} | |
//using slice to concat remaining items left in either arrA or arrB | |
return result.concat(arrA.slice(a)).concat(arrB.slice(b)); | |
} | |
//usage: | |
mergeSort([4,2,8,3,6,9,1]); //=> [1,2,3,4,6,8,9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment