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;
}

--

--

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