Last active
November 24, 2022 22:27
-
-
Save IsraaMoqbel/746bd5908beeed8234b3a59f15a35008 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 mergeSort(arr) { | |
| if (arr.length <= 1) { | |
| return arr | |
| } | |
| const middlePoint = Math.floor(arr.length / 2); | |
| const rightArray = arr.slice(middlePoint); | |
| const leftArray = arr.slice(0, middlePoint); | |
| return merge(mergeSort(leftArray), mergeSort(rightArray)); | |
| } | |
| function merge(left, right) { | |
| let arr = []; | |
| while (right.length && left.length) { | |
| if (left[0] < right[0]) { | |
| arr.push(right.shift()) | |
| } else { | |
| arr.push(left.shift()) | |
| } | |
| } | |
| return [...arr, ...left, ...right] | |
| } | |
| console.log(mergeSort([3, 5, 9, 7, 4])); // [ 9, 7, 5, 4, 3 ] | |
| // Time complixity is O(nlogn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment