## DEV Community Qayyum Shareef

Posted on • Updated on

# Linear Search Algorithm | JavaScript

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.

## 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)
``````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) {
}
}

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!

DEV Community ## 11 Tips That Make You a Better Typescript Programmer

### 1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

### #2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

...