Searching and Sorting Algorithms in Javascript — Part 8 (Linear Search).
I should have started this series with searching (as the title implies) but somehow, It felt right to do the sorting algorithms first. Over the span of 6–7 parts, we’ve been able to address the following sorting algorithms:
In this part (or chapter), we’ll be looking at a searching algorithm called the Linear search algorithm. This algorithm is pretty straightforward and the implementation is also very straightforward.
Searching (in general) usually involve trying to locate an item in the midst of other items, e.g: Looking for a book in a physical library, Searching for your future parter admist over 7 billion people on earth, an so on…
If you’re to use linear search algorithm to locate an item, you can easily do that by looping through all the possible items and compare it to the item you’re looking for, if there’s a match at any point in time, return the item, if not, just return -1 (or something that indicates that what you’re looking for is not in the list provided).
The above implementation was structured to return an Object containing a message, the item that was found and the index of the first occurrence of the item. The commented returns in the code signifies what is usually returned from the algorithm in most cases.
You can quickly see that, as much as this is pretty straightfoward, it can be very slow if you’re searching through more complex data structures like an object in an array of objects or array of an array of arrays (a multidimensional array.
Anyways, that’s all there is to know about linear search, see you on the next one!