C Program:Linear search using recursion


Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.

PROGRAM:

#include<stdio.h>
void ReadArray(int a[10],int n)
{
    int i;
    printf("\nEnter elements");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
}

int recSearch(int a[10], int l, int r, int x)
{
     if (r < l)
        return -1;
     if (a[l] == x)
        return l;
     if (a[r] == x)
        return r;
     return recSearch(a, l+1, r-1, x);
}

int main()
{
    int a[10],n,x;
    printf("\nEnter the size of an array");
    scanf("%d",&n);
    ReadArray(a,n);
    printf("\n Enter the key element");
    scanf("%d",&x);
    int index = recSearch(a, 0, n-1, x);
    if (index != -1)
       printf("Element %d is present ", x);
    else
        printf("Element %d is not present", x);
    return 0;
Previous Post Next Post