diff --git a/Recursive/RecursiveLinearSearch.js b/Recursive/RecursiveLinearSearch.js new file mode 100644 index 0000000000..9b02132527 --- /dev/null +++ b/Recursive/RecursiveLinearSearch.js @@ -0,0 +1,28 @@ +// Explanation:- https://www.geeksforgeeks.org/recursive-c-program-linearly-search-element-given-array/ + +/** + * Recursive Linear Search + * + * This function searches for a key within an array using a recursive approach. + * + * @param {Array} arr - The array to search within. + * @param {*} key - The element to search for. + * @param {number} index - (Optional) The current index being checked in the array (default is 0). + * @returns {number} - The index of the element if found, or -1 if not found. + */ +function recursiveLinearSearch (arr, key, index = 0) { + // Base case: If we have searched the entire array and haven't found the key, return -1. + if (index === arr.length) { + return -1 + } + + // Base case: If the current element matches the key, return its index. + if (arr[index] === key) { + return index + } + + // Recursive case: Continue searching in the rest of the array. + return recursiveLinearSearch(arr, key, index + 1) +} + +export { recursiveLinearSearch } diff --git a/Recursive/test/RecursiveLinearSearch.test.js b/Recursive/test/RecursiveLinearSearch.test.js new file mode 100644 index 0000000000..2a7daa25a3 --- /dev/null +++ b/Recursive/test/RecursiveLinearSearch.test.js @@ -0,0 +1,30 @@ +import { recursiveLinearSearch } from '../RecursiveLinearSearch' + +describe('RecursiveLinearSearch', () => { + const arr = [2, 3, 4, 10, 25, 40, 45, 60, 100, 501, 700, 755, 800, 999] + + it('should return index 3 for searchValue 10', () => { + const searchValue = 10 + expect(recursiveLinearSearch(arr, searchValue)).toBe(3) + }) + + it('should return index 0 for searchValue 2', () => { + const searchValue = 2 + expect(recursiveLinearSearch(arr, searchValue)).toBe(0) + }) + + it('should return index 13 for searchValue 999', () => { + const searchValue = 999 + expect(recursiveLinearSearch(arr, searchValue)).toBe(13) + }) + + it('should return -1 for searchValue 1', () => { + const searchValue = 1 + expect(recursiveLinearSearch(arr, searchValue)).toBe(-1) + }) + + it('should return -1 for searchValue 1000', () => { + const searchValue = 1000 + expect(recursiveLinearSearch(arr, searchValue)).toBe(-1) + }) +})