Skip to content

Instantly share code, notes, and snippets.

@leolanese
Last active April 10, 2020 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leolanese/c6c0d1171cdad30a5943d11400c62b79 to your computer and use it in GitHub Desktop.
Save leolanese/c6c0d1171cdad30a5943d11400c62b79 to your computer and use it in GitHub Desktop.
Sorting algorithms JS: Merge Sort (Recursion)
//
// Merge Sort Implentation (Recursion)
//
function mergeSort (unsortedArray) {
// No need to sort the array if the array only has one element or empty
if (unsortedArray.length <= 1) {
return unsortedArray;
}
// In order to divide the array in half, we need to figure out the middle
const middle = Math.floor(unsortedArray.length / 2);
// This is where we will be dividing the array into left and right
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
// Using recursion to combine the left and right
return merge(
mergeSort(left), mergeSort(right)
);
}
// Merge the two arrays: left and right
function merge (left, right) {
let resultArray = [], leftIndex = 0, rightIndex = 0;
// We will concatenate values into the resultArray in order
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++; // move left array cursor
} else {
resultArray.push(right[rightIndex]);
rightIndex++; // move right array cursor
}
}
// We need to concat to the resultArray because there will be one element left over after the while loop
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
/*
Merge
sort
is
a
recursive
way
to
sort
an
array.

First,
you
divide
the
array
in
half
and

recursively
sort
each
half
of
the
array.

Then,
you
combine
the
two
halves
into
a

sorted
array.

ref:
https://medium.com/javascript-in-plain-english/javascript-merge-sort-3205891ac060
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment