Last active
January 26, 2020 07:52
-
-
Save BrooklinJazz/d1be0c1389bd873486521439793798ad to your computer and use it in GitHub Desktop.
a documented example of the merge function in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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