DEV Community

Discussion on: Linear and Binary Search in JavaScript

Collapse
 
linaran profile image
Deni

Linear searches are slower than binary searches but they aren't inherently bad and binary searches aren't always better.

If you have a use case where you often need to add elements to your array, keeping your array sorted can be very expensive. Sorting algorithms are usually O(n*log n) complexity and that may be slower than performing a simple linear search on your array.

So depending on your use case linear search can be perfectly fine.

Collapse
 
stephjs profile image
Steph

That's true, it depends on your data set. Assuming it's sorted and you're only worried about the run time of the search, a linear search is O(n) while a binary search is O(log n).