Skip to content

Instantly share code, notes, and snippets.

@BrooklinJazz
Last active January 26, 2020 07:52
Show Gist options
  • Select an option

  • Save BrooklinJazz/d1be0c1389bd873486521439793798ad to your computer and use it in GitHub Desktop.

Select an option

Save BrooklinJazz/d1be0c1389bd873486521439793798ad to your computer and use it in GitHub Desktop.
a documented example of the merge function in javascript
// 1. merge takes an already sorted left half and already sorted right half of the original array.
const merge = (left, right) => {
let resultArr = [];
let leftIndex = 0;
let rightIndex = 0;
// 2. merge crawls over these arrays creating a resulting array from the smallest values until either the left or right array is empty.
while ((leftIndex < left.length, rightIndex < right.length)) {
if (left[leftIndex] < right[rightIndex]) {
resultArr.push(left[leftIndex]);
leftIndex++;
} else {
resultArr.push(right[rightIndex]);
rightIndex++;
}
}
return resultArr
// 3. lastly merge pushes the remaining elements of the left or right array into the result.
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment