Basic Solutions to Sorting Algorithms: Merge Sort

lmao
while (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift())
} else {
results.push(right.shift())
}
}
function merge(left, right) { 
let results = []
while (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift())
} else {
results.push(right.shift())
}
}
return [...results, ...left, ...right]
}
function mergeSort(arr) {
if (arr.length === 1) {
return arr
}

let center = Math.floor(arr.length / 2)
let left = arr.slice(0, center)
let right = arr.slice(center)
return merge(mergeSort(left), mergeSort(right))}
merge sort diagram
I couldn’t find anymore merging gifs, so here’s a sorting one!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How F# made me appreciate JavaScript

Breaking Down Drag N’ Drop

Using JavaScript methods to update Chart.js data

What happens when you type ls *.c into your shell

Day 57 | 100 Days Full-Stack Challenge

Question since how final natural.

Frontend Interview Question: Create a Star Rating UI

Understanding Method Chaining In Javascript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
HopeGiometti

HopeGiometti

More from Medium

CS373 Spring 2022: Nathan Whyte

CS373 Spring 2022: Shreya Sridhar

What is Node.js and why you need it?

CS373 Spring 2022: Ruchi Bhalani Week 11