Linear search

Linear search is the simplest and least performant searching algorithm we’ll cover. Literally, all it is is loop over the array until you find what you’re looking for. Below is a three minute video from Harvard that explains the linear search algorithm more thoroughly.

Linear search explained.

This will not likely be covered in interviews as it is the least performant. If you do write a loop that traverses an array and the interviewer asks how your search can be optimized, be prepared to discuss one of the other algorithms below.

Linear search is not performant because in order to find the element in the worst case the computer will have to examine every single item in the array. Linear search can be implemented with the Javascript code below.

Linear search implemented in Javascript.

In the worst case scenario we have to look at every item in the array. That means it would run in O(n) complexity.

Binary search

Binary search is more efficient than linear search; it has a time complexity of O(log n). The list of data must be in a sorted order for it to work.

A binary search works by finding the middle element of a sorted array and comparing it to your target element. Based on what you find, you either use the left or right half of the array and update the start and ending indexes until you either do or do not find the element. Thanks to Yangshun Tay’s tech interview handbook for the code.

Below is another video from the CS50 course explaining binary search.

Binary and linear search algorithms can both be used to find elements in a list using Javascript. If you have any questions feel free to reach out via twitter.