diff --git a/csci/fib.js b/csci/fib.js new file mode 100644 index 0000000..51b7623 --- /dev/null +++ b/csci/fib.js @@ -0,0 +1,39 @@ +function loopFib(seq) { + let first = 0; + let second = 1; + let final = []; + + if (seq < 1) return first; + + for (let i = 1; i < seq; i++) { + if (first === 0) { + final.push(first); + first = 1; + } else { + let temp = second; + second = first + second; + first = temp; + } + final.push(first); + } + + console.log(final); +} + +function recursiveFib(seq) { + if (seq === 1) { + return [0]; + } else if (seq === 2) { + // if (seq < 2) { + return [0, 1]; + } else { + let arr = recursiveFib(seq - 1); + arr.push(arr[arr.length - 1] + arr[arr.length - 2]); + return arr; + } +} + +let num = process.argv[2]; + +loopFib(num); +console.log(recursiveFib(num)); diff --git a/csci/mergeSort.js b/csci/mergeSort.js new file mode 100644 index 0000000..2c1b8ba --- /dev/null +++ b/csci/mergeSort.js @@ -0,0 +1,33 @@ +function mergeSort(arr) { + if (arr.length <= 1) { + return arr; + } else { + let half = Math.round(arr.length / 2); + let leftSide = mergeSort(arr.slice(0, half)); + let rightSide = mergeSort(arr.slice(half, arr.length)); + + let newArr = mergeArray(leftSide, rightSide); + + return newArr; + } +} + +function mergeArray(left, right) { + let sorted = []; + + while (left.length && right.length) { + if (left[0] < right[0]) { + sorted.push(left.shift()); + } else { + sorted.push(right.shift()); + } + } + return sorted.concat(left, right); +} +let testCaseOne = [2, 1, 3, 9, 4, 5, 23, 10]; + +let testCaseTWo = [23, 5, 3, 1, 8, 7, 2, 4]; +console.log(`Test Case No1: ${testCaseOne}`); +console.log(mergeSort(testCaseOne)); +console.log(`Test Case No2: ${testCaseTWo}`); +console.log(mergeSort(testCaseTWo));