Skip to content

Instantly share code, notes, and snippets.

@softy-dev
Last active October 9, 2024 22:27
Show Gist options
  • Select an option

  • Save softy-dev/ad9fbd7143e13b6e10962523f797719b to your computer and use it in GitHub Desktop.

Select an option

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.
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);
}
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));
}
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