Last active
July 2, 2020 19:49
-
-
Save Dornhoth/8985ff4d3f9cab3eb8e421fc2ac690df to your computer and use it in GitHub Desktop.
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
| function merge(left, right) { | |
| const result = []; | |
| while (left.length > 0 && right.length > 0) { | |
| if (left[0] <= right[0]) { | |
| result.push(left[0]); | |
| left = left.slice(1); | |
| } else { | |
| result.push(right[0]); | |
| right = right.slice(1); | |
| } | |
| } | |
| while (left.length > 0) { | |
| result.push(left[0]); | |
| left = left.slice(1); | |
| } | |
| while (right.length > 0) { | |
| result.push(right[0]); | |
| right = right.slice(1); | |
| } | |
| return result; | |
| } | |
| function mergeSort(array) { | |
| if (array.length <= 1) { | |
| return array; | |
| } | |
| let left = []; | |
| let right = []; | |
| for (let i = 0; i < array.length; i += 1) { | |
| if (i < array.length / 2) { | |
| left.push(array[i]); | |
| } else { | |
| right.push(array[i]); | |
| } | |
| } | |
| left = mergeSort(left); | |
| right = mergeSort(right); | |
| return merge(left, right); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment