Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Recursive/RecursiveLinearSearch.js
Original file line number Diff line number Diff line change
@@ -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 }
30 changes: 30 additions & 0 deletions Recursive/test/RecursiveLinearSearch.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})