Read · 1 min
Linear Search
The linear search is just going from the first element to a last element of your data, stopping if you find the element you're looking for. In the worst case, if you have terms to search through, so this algorithm runs in .
Binary Search
Binary search is a great search that works when your data is already in order. Think of it as that game where Player 1 thinks of a number, and Player 2 must try to guess that number after Player 1 says lower or higher. Well binary search does just that.
Since the data is already in order, we will know when we have passed an element. So if we have elements, look at element . If it is too high, then perform the algorithm in the interval . If it is too low, then perform the algorithm in the interval .
Say we wanted to find the index of the element in the array . Since there are elements, look at the th element, . This is too low, so look in the interval . Check the middle term, the th term, which is . This is too high again, so check in the interval . Check the middle term, the th term. This is too low again, so check the th term and we win.
The binary search algorithm runs in since if you have elements, it will need to halve times to terminate. (By the way: is really good! It certainly pays off to keep your data sorted if you plan on searching in it a lot.)