Master recursion through classic algorithms: Fibonacci sequence generation and Merge Sort implementation
This project explores recursion through two fundamental computer science problems as part of The Odin Project's Full Stack JavaScript curriculum.
Algorithms implemented:
- Fibonacci Sequence - Both iterative and recursive implementations
- Merge Sort - Recursive divide-and-conquer sorting algorithm
- Node.js >= 14.0.0 - Download here
node index.jsFibonacci:
node -e "import('./fibonacci.js').then(m => console.log(m.fibs(8)))"
node -e "import('./fibonacci.js').then(m => console.log(m.fibsRec(8)))"Merge Sort:
node -e "import('./mergeSort.js').then(m => console.log(m.mergeSort([3,2,1,13,8,5,0,1])))"Iterative:
fibs(8) // Returns: [0, 1, 1, 2, 3, 5, 8, 13]Recursive:
fibsRec(8) // Returns: [0, 1, 1, 2, 3, 5, 8, 13]Test Cases:
mergeSort([]) // Returns: []
mergeSort([73]) // Returns: [73]
mergeSort([1, 2, 3, 4, 5]) // Returns: [1, 2, 3, 4, 5]
mergeSort([3, 2, 1, 13, 8, 5, 0, 1]) // Returns: [0, 1, 1, 2, 3, 5, 8, 13]
mergeSort([105, 79, 100, 110]) // Returns: [79, 100, 105, 110]Complexity:
- Time: O(n log n)
- Space: O(n)
- Iterative approach uses a loop to build the sequence
- Recursive approach uses function calls with an accumulator array
- Both handle edge cases (n = 0, n = 1)
- Uses divide-and-conquer strategy
- Recursively splits arrays until reaching single elements
- Merges sorted subarrays back together
- Handles arrays with duplicates and negative numbers
- Recursion - Functions calling themselves with modified parameters
- Base cases - Conditions to stop recursive calls
- Array methods -
slice(),push(),length - ES6 modules -
import/exportsyntax - Helper functions -
merge()for combining sorted arrays
All test cases from The Odin Project assignment are included in index.js:
- Empty arrays
- Single elements
- Already sorted arrays
- Reverse sorted arrays
- Arrays with duplicates
This project is licensed under the MIT License.
The things I learned from this project are:
- Using
slicearray function to split an array for merge sort - Sorting each subarray (left and right) via recursion
Part of The Odin Project: Full Stack JavaScript Path