Last active
October 9, 2024 22:27
-
-
Save softy-dev/ad9fbd7143e13b6e10962523f797719b to your computer and use it in GitHub Desktop.
Use of recursion in well-known Fibonacci sequence and Merge Sort functions.
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
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 fibs(length) { | |
| if (!Number.isInteger(length) || length < 1) return; | |
| const sequence = [0, 1]; | |
| for (let i = 2; i < length; i++) { | |
| sequence.push(sequence[i - 1] + sequence[i - 2]); | |
| } | |
| return sequence.slice(0, length); | |
| } |
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 fibsRec(length) { | |
| if (!Number.isInteger(length) || length < 1) return; | |
| if (length <= 2) return [0, 1].slice(0, length); | |
| const sequence = fibsRec(length - 1); | |
| return sequence.concat(sequence.at(-1) + sequence.at(-2)); | |
| } |
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(array) { | |
| if (array.length <= 1) return array; | |
| let left = array.slice(0, array.length / 2); | |
| let right = array.slice(array.length / 2); | |
| if (left.length > 1) { | |
| left = mergeSort(left); | |
| } | |
| if (right.length > 1) { | |
| right = mergeSort(right); | |
| } | |
| function merge(left, right) { | |
| const sortedArray = []; | |
| if (left.length > 0 && right.length > 0) { | |
| if (left[0] < right[0]) { | |
| sortedArray.push(left.shift()); | |
| } else { | |
| sortedArray.push(right.shift()); | |
| } | |
| return sortedArray.concat(merge(left, right)); | |
| } | |
| if (left.length === 0) return sortedArray.concat(right); | |
| if (right.length === 0) return sortedArray.concat(left); | |
| } | |
| return merge(left, right); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment