Merge Sort in JavaScript —

Notice the numbered steps. left side then right side.
function mergeSort (unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
// Using recursion to combine the left and right
//this is breaking down the left and right side into sorted arrays
// eachtime mergeSort is called in the parameters the left and right // are unique to the side it started on.

return merge(
mergeSort(left),
mergeSort(right)
);
}
function merge (left, right) {
let resultArray =[], leftIndex=0, rightIndex=0;
//Here are are looping through our arrays and itterating using
//closure

while (leftIndex < left.length && rightIndex < right.length) {
//Here we are sorting our arrays by index values and pushing //into our newly created array that will be returned.
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
//Note; you could just return the result array, I did this for console.logging purposes for a better understanding of the code.
//result array is adding the left and right to its value.

let target = resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
return target;
}

--

--

--

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

Recommended from Medium

SVELTE.JS Better than React.Js?

Check if a number is majority element in the sorted array

Drupal and React/TypeScript components

Drupal and React/TypeScript

When and Where to use Const, Let and Var

Pros and Cons of JavaScript: Choose Wisely

JavaScript Some Key Topics

Using NativeBase v3 the right way

Throttling notifications from multiple users with RxJS

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
Anthony Johnson

Anthony Johnson

More from Medium

learning JavaScript backend, finally

Project-DERMSTORE

Data Structures in JavaScript: Node

Linked Lists in Javascript