# Linear Search

Linear Search is the simplest and easiest searching algorithm. Linear search algorithm works by simply finding the desired element from start to end of the list.

Linear search algorithm returns the index position of the element, if found in the list, else, returns false or invalid index position (i.e., -1).

#### WORKING OF LINEAR SEARCH

Suppose we want to find the element 13 in the array of 6 elements. Then, linear search algorithm will work as follows:

The linear search algorithm will work by traversing the whole array from beginning to end until it founds the element.

Example:

Element 13 is found at index position ‘5’. Hence, 5 will be returned.

ALGORITHM:

```Algo Linear_search (arr, key)
{
// input – key to be searched and array from which it needed to be searched.
// output -   return the index position of the element to be searched, else return -1.
1. i=0 .
2. Loop(i < sizeof(arr))
{
1.  If(arr[i] == key)
2. Return i.
}
3.  return -1.
}//END

```

#### C++ Program to Implement Linear Search is as follows:

```#include<bits/stdc++.h>
using namespace std;
int linearSearch(int arr[],int size,int ele)
{
// Traversing every element of the array
for(int i = 0 ; i < size ; i++)
{
// If element is present in the array
if(arr[i] == ele)
return i+1;
}
// If element is not present in the array
return -1;
}
int main()
{
int arr[] = { 46 , 59 , 11 , 67 , 13 , 97 } ;
int size = sizeof(arr) / sizeof(arr);
int ele = 13;
int res = linearSearch(arr,size,ele);
if(res == -1)
cout<<ele<<" is not present in the array";
else
cout<<ele<<" is present at "<<res<<" position";
}

```
```OUTPUT:
13 is present at 5
Time Complexity:
The time Complexity of the Linear Search Algortihm is O(n).
Where ‘n’ is the number of elements in the array.```

Related Posts: