Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
Though it is very easy in JavaScript to find index of an item in a list using indexOf method:
list.indexOf(item)
but sometimes you might need to do some customization on the searching algorithm. Like- 'finding the last occurrence of the item in the list' etc. This linear search implementation will help you to do that.
- Worst Case - O(n)
- Best Case - O(1)
- Average Case - O(n)