Linear search algorithm

·

1 min read

code in c lang

#include <stdio.h>
int l_search(int a[], int n,int item)
{
    int loc=-1;
    for (int i=0;i<n;i++)
    {
        if (a[i]==item)
        {
            return loc=i;
        }
    }
    return loc;
}
int main() {
  int res,item,n;
  printf("Enter the size of an arrray:");
  scanf("%d",&n);
  int a[n];
  for (int i=0;i<n;i++)
  {
      printf("A[%d]: ",i);
      scanf("%d",&a[i]);
  }
  printf("Enter the item to be searched:");
  scanf("%d",&item);
  res=l_search(a,n,item);
  if (res==-1)
  {
      printf("Elememt not found");
  }
  else{
      printf("Element found at index %d",res);
  }


    return 0;
}

code in python

data=[29,75,69,22,2,95]
def l_search(a,n,item):
    loc =-1
    for i in range(n):
        if a[i]==item:
            loc=i
    return loc


res=l_search(data,len(data),22)
if res==-1:
    print("Element not found")
else:
    print("Element found at index:",res)