VOOZH about

URL: https://www.geeksforgeeks.org/dsa/recursive-c-program-linearly-search-element-given-array/

⇱ Linear Search Using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Linear Search Using Recursion

Last Updated : 27 Sep, 2025

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 found

Input: 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

How Does Linear Search Work?

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.

Approach :-

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.


Output
2

Time Complexity:

  • Best Case: In the best case, the key might be present at the last index. So the best case complexity is O(1).
  • Worst Case: In the worst case, the key might be present at the first index i.e., opposite to the end from which the search has started in the list. So the worst case complexity is O(n) where n is the size of the list.
  • Average Case: O(n)

Auxiliary Space: O(n) recursion stack space.

Comment
Article Tags: