Created
March 24, 2021 20:31
-
-
Save YenHub/143bc0d93972db830c63328e07f711cf to your computer and use it in GitHub Desktop.
Javascript Merge Sort
This file contains hidden or 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
// For each side of a set of arrays | |
const mergeArrays = (left, right) => { | |
// Iterate each 0th value moving the vaues into our sorted array | |
let sortVals = []; | |
while(left.length && right.length) { | |
(left[0] < right[0]) ? sortVals.push(left.shift()) : sortVals.push(right.shift()); | |
} | |
// Return sorted array & anything leftover from either side | |
return [...sortVals, ...left, ...right]; | |
}; | |
// A recursive function which will return a sorted array | |
const mergeSort = array => { | |
// Base case | |
if(array.length === 1) { | |
return array; | |
} | |
// Split our array | |
let left = []; | |
const midPoint = array.length / 2; | |
while (left.length < parseInt(midPoint)) { | |
left.push(array.shift()); | |
} | |
// Recursively split & merge (sort) our arrays | |
return mergeArrays(mergeSort(left), mergeSort(array)); | |
}; | |
// Usage | |
// First Get an array of randomish numbers :p | |
var array = []; | |
for(var i = 0; i < 100000; i++) { | |
let newVal = 0; | |
while(newVal < 1) { | |
let valA = Math.random() * 9; | |
let valB = Math.random() * 14; | |
let rand = Math.random() * 10; | |
newVal = parseInt((valA + valB) / rand); | |
} | |
array.push(newVal); | |
} | |
// Call the recursive function with your array | |
console.log(mergeSort(array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment