Open In App

Recursive Linear Search Algorithm

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set.

How Linear Search Works?

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.

Pseudocode for Recursive Linear Search:

LinearSearch (array, index, key):
    if index < 0:
        return -1;
    if item = key:
        return index
    return LinearSearch (array, index-1, key)

Implementation of Recursive Linear Search:

Below is the recursive implementation of linear search:

C++14
// C++ Recursive Code For Linear Search
#include <bits/stdc++.h>
using namespace std;

int linearsearch(int arr[], int size, int key)
{
    if (size == 0) {
        return -1;
    }
    else if (arr[size - 1] == key) {
        
        // Return the index of found key.
        return size - 1;
    }
    return linearsearch(arr, size - 1, key);
}

// Driver Code
int main()
{
    int arr[] = { 5, 15, 6, 9, 4 };
    int key = 4;

    // Function call
    int ans = linearsearch(arr, 5, key);
    if (ans == -1) {
        cout << "The element " << key << " is not found."
             << endl;
    }
    else {
        cout << "The element " << key << " is found at "
             << ans << " index of the given array." << endl;
    }
    return 0;
}
C Java Python C# JavaScript PHP

Output
The element 4 is found at 4 index of the given array.

Complexity Analysis:

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(1) as this is a tail recursion, so no recursion stack space is utilized.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg