In this article, you’ll learn how to implement the linear search algorithm using recursion in C++, Python, JavaScript, and C.

Problem Statement

You’re given an unsorted array and an element to be searched in the given array. You need to write a recursive function such that if the element is found in the given array, the index of the element is returned and if the element is not found in the array, -1 is returned.

Example 1: Let arr = [1, 2, 3, 4, 5, 6, 7] and elementToBeSearched = 4

4 is present in the array at index 3.

Thus, 3 is returned from the function and “Element 4 found at index 3” is displayed on the output.

Example 2: Let arr = [1, 1, 1, 1, 1] and elementToBeSearched = 2

2 is not present in the array.

Thus, -1 is returned from the function and “Element 2 not found” is displayed on the output.

Approach to Solve the Problem

Compare the element to be searched with the element at the left-most index and the right-most index in the array. If the element is found, return the index. Else recursively search the element for the rest of the array by incrementing the left index and decrementing the right index. Call the function recursively until the right index is less than the left index.

C++ Program to Implement the Linear Search Algorithm Using Recursion

Below is the C++ program to implement the linear search algorithm using recursion:

Output:

Python Program to Implement the Linear Search Algorithm Using Recursion

Below is the Python program to implement the linear search algorithm using recursion:

Output:

JavaScript Program to Implement the Linear Search Algorithm Using Recursion

Below is the JavaScript program to implement the linear search algorithm using recursion:

Output:

C Program to Implement the Linear Search Algorithm Using Recursion

Below is the C program to implement the linear search algorithm using recursion:

Output:

Learn Recursion

Recursion is a very important and fun programming topic. Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It might be a little difficult to learn for beginner programmers, but learning how to solve problems using recursion is worth it.