![]() |
VOOZH | about |
Given an array arr[] of integers and an integer key, write a recursive function to perform linear search that check whether the key exists in the array or not. If it exists, return its index otherwise, return -1.
Examples:
Input: arr[] = [10, 20, 30, 40, 50], key = 30
Output: 2
Explanation:
Start at index 0: Element = 10, not equal to 30
Move to index 1: Element = 20, not equal to 30
Move to index 2: Element = 30, match foundInput: arr[] = [15, 25, 35, 45], key = 50
Output: -1
Explanation :
Start at index 0: Element = 15, not equal to 50
Move to index 1: Element = 25, not equal to 50
Move to index 2: Element = 35, not equal to 50
Move to index 3: Element = 45, not equal to 50; Return -1
Linear search works by comparing each element of the data structure with the key to be found. To learn the working of linear search in detail, refer to this post.
The function recursively checks elements from the start of the array. If the current element matches the key, it returns its index; otherwise, it searches the remaining elements. The base case occurs when the size of the array becomes zero, meaning the element is not found.
2
Time Complexity:
Auxiliary Space: O(n) recursion stack space.