Linear search or sequential search is a method for finding an element within a list.
It sequentially checks each element of the list until a match is found or the whole list has been searched.
Linear Search algorithm returns the index of element in array if it is found, or return -1 if element is not present in the given array.
Time complexity = O(N).
Space Complexity = O(1).
C++ Code for Linear search.
#include<iostream>usingnamespacestd;
intmain(){
int n,i,x,index=-1;
cout<<"Enter no. of elements \n";
cin>>n;
int a[n];
cout<<"Enter elements of array\n";
for(i=0 ; i<n ; i++)
{
cin>>a[i];
}
cout<<"Enter element to be Searched\n";
cin>>x;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
index=i;
break;
}
}
if(index==-1) cout<<"Element not found.\n";
else {
cout<<"Element found at index "<<index<<"\n";
}return0;
}
Comments