In Linear Search or Sequential Search every element in the array is checked, and if the match is found then the element index is returned, otherwise the search continues till the last element.

Visual learners can follow my YouTube video.

## Lets write some code

Always remember that array indexing starts from Zero - '0'

```
const numbers = [2, 4, 67, 8, 44, 6, 12];
```

Now, lets write a function to apply linear search algorithm to above array.

```
function linearSearch(array, num) {
for (let i = 0; i < array.length; i++) {
if (array[i] === num) {
return i;
}
}
return -1;
}
linearSearch(numbers, 8); // returns index 4
linearSearch(numbers, 28); // since 28 is not there, returns -1
// Save the file and run it using Node.JS
// Open terminal and give command: node [filename].js
```

## Time Complexity

The time complexity of Linear Search Algorithm is O(n).

let's improve the worst case scenario.

- If the search element found at last. O(n) -> O(1)
- If the search element not found. O(n) -> O(n/2)

```
function betterLinearSearch(array, element) {
let length = array.length;
let left = 0;
let right = length - 1;
let position = -1;
while (left <= right) {
if (array[left] == element) {
position = left;
console.log(`${element} is present at index ${position}. attempt ${left + 1}`);
break;
}
if (array[right] == element) {
position = right;
console.log(`${element} is present at index ${position}. - attempt ${length - right}`);
break;
}
left++;
right--;
}
if (position == -1) {
console.log(`${element} not found. attempt ${left}`);
}
}
betterLinearSearch(numbers, 8);
// Try with a last element and check the attempts in log
betterLinearSearch(numbers, 12);
betterLinearSearch(numbers, 28);
// Save the file and run it using Node.JS
// Open terminal and give command: node [filename].js
```

- In every iteration, first and last element from the array is being checked.
- After every iteration the left index needed to be increased and right index needed to be decreased.
- When position value remains
`-1`

it means the element is not present in array.

Well, that's it folks. I hope you learned something share it with your friends. Follow me for more posts just like this and let me know your thoughts in the comment section.

Cheers!

## Discussion (0)