arrays Archives - Michiel Arkema's Blog https://blog.michielarkema.com/tag/arrays/ The Official blog of Michiel Arkema Fri, 10 Feb 2023 10:59:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 214496708 Linear Search, The Simplest Search Algorithm https://blog.michielarkema.com/coding-secrets/linear-search-the-simplest-search-algorithm/ https://blog.michielarkema.com/coding-secrets/linear-search-the-simplest-search-algorithm/#comments Fri, 10 Feb 2023 10:59:06 +0000 https://blog.michielarkema.com/?p=162 The Linear Search algorithm is the most basic algorithm that you can use for searching elements inside Collections. That’s why in this blog post, you are going to discover exactly…

The post Linear Search, The Simplest Search Algorithm appeared first on Michiel Arkema's Blog.

]]>
The Linear Search algorithm is the most basic algorithm that you can use for searching elements inside Collections.

That’s why in this blog post, you are going to discover exactly what they linear search algorithm is, how it works and how you can use it.

For the following example, we’ll use JavaScript, but you can use it for any programming language you desire.


What is the Linear Search Algorithm?

Well let’s imagine you have a list of numbers ranging from 10 to 100.

const numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Now, let’s say you want to search for the number 60 and retrieve its index number. Well, there are two easy ways to achieve this, we can either grab the number directly by its index (assuming we know the index number already) or, we can perform a linear search that goes over each number in the list, compares it with our target number and return it’s index if it matches.

How to execute the Linear Search Algorithm?

So to execute a linear search, we have to create an iterator that iterates based on the length of the list. To do this, add the following code…

// Let's get the length of the list first.
const length = numbers.length

// The iterator
for(let i = 0; i < length; i++) {
  // Now, let's check if the value matches the number 60 or not.
  if(numbers[i] == 60) {
    return i;
  }
}

How does it work?

Now, you might still be asking yourself, how does it work and why is it linear?

The reason why it’s a linear search is because it walks over the list from beginning to end without skipping over any.

So in this example, it will start at the number 10, then it will go over each element and ends with the number 60 (since that’s our target number).


Are there any drawbacks to using this?

Yes definitely!

The drawback that you need to be aware of when using this algorithm and that it is not suited for large collections due to its time complexity.

It’s perfect for smaller collections.


The post Linear Search, The Simplest Search Algorithm appeared first on Michiel Arkema's Blog.

]]>
https://blog.michielarkema.com/coding-secrets/linear-search-the-simplest-search-algorithm/feed/ 2 162