Search code examples
searchbig-obinary-searchsequential

Which search algorithm to prefer?


Binary search algorithm has a big O value of O(log n) and a sequential search has a big O value of O(n). But we need sorting algorithm before a binary search and best big O value for a sorting algotithm is O(n.log n). So, effectively, the big O value for binary search is O(n.log n), which is greater than that of the sequential search. So, which one is preferred as searching algo?


Solution

  • In practice it depends on how often you search. If you have to search millions of times, you want binary search, even if you have to pay the upfront cost of sorting. It depends on your use case. With binary search, you also ensure that your inserts keep the list sorted, so they become slower as well.

    If you need to do a lot of inserts, and very few searches, sequential search might be faster.

    Keep in mind that a lot of this won't even be noticeable until you are working with a lot of data.