Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 19, 2021 07:39 pm GMT

Linear Search Algorithm | JavaScript

Hi there, 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 4linearSearch(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 for the above code 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 logbetterLinearSearch(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 for this article. I hope you learned something. Follow me for more posts just like this and let me know your thoughts in the comment section.

Share this post with your friends who needs to learn algorithms. Thanks


Original Link: https://dev.to/mdqayyumshareef/linear-search-algorithm-javascript-mb4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To