Linear Search : Understanding and Implementing | Searching Algorithms

Linear Search : Understanding and Implementing | Searching Algorithms


linear search implementation understand search algorithms



Intro :

There a lot of sorting algorithms that exist today like - Binary Search, Linear  Search , Interpolation Search , Jump Search and many more .But the most basic one and the one search algorithm that most people learn when they learn to sort and search for the first time is Linear Search

In this blog we are going to learn the algorithm by understanding how it works ,it's implementation and it's time complexity .

Linear Search :

An algorithm which is used to find all the prime numbers in a given range .

Time Complexity : O(n)

 The Idea :

        So, the idea of the algorithm is simply that we find the required element by going through the whole range of given elements starting from one end to another.

Understanding the algorithm :

   Lets assume we are given a number a set of elements :{ 4 , 5 , 6 , 9 , 10 , 11 }. And we have to find 5 in the given range .So what we do is that we go through each of the element in the given range like - first 4 and we check is this equal to the our element ? So, as 4 is not  equal to 9 we do the same with the next numbers until the we stop which is when we reach 9 after going through 4 -> 5 -> 6 and 9.Thus we print that the element is found . And if we reach the end of the array and non of the element matches with our required element then we conclude that there is no such element in our range . 

The Code :


From the Classical Algorithm Reposititory. Do give a star ! ๐ŸŒŸ

Implementation :

✔️First we make an array which contains the given set of elements and store the element to be searched in a variable               

✔️We make a loop to traverse through the whole set and thus this step makes this an algorithm which runs on linear time i.e. O(n).

✔️In each iteration inside the loop we check whether the current element is equal to the element we are searching for .

✔️If it is equal at some point then we return 'true' that that it is found and thus getting out of the loop. Thus, making it obvious that if we traverse till the end of the loop and get out of the loop after the last iteration then we have not found the element and thus we return 'false'.                           

So, that's how in linear time we know that whether there is an element in the given array or not . 

Thanks, Keep Learning ๐Ÿงก