Binary Search vs For loop
so I did this
and surprisingly the for loop did it in less time.. shouldn't binary search be faster?? 🤔
or am I doing it wrong??
3 Replies
Now do the same thing but with 10k elements and see which is faster. Then 100k.
only 100 elements is a very small dataset and isn't what binary searches are optimized for
No one algorithm is a silver bullet that will do everything. With only 100 elements it's taking more time to split and search than it is to find. But with a larger dataset the splitting time will make the search time that much faster. Big O is, like everything CS-related, a suggestion/guideline that doesn't take every situation into account. It's a "close enough".
hmm i see.. Yaa it makes sense tnx ❤️
It's similar to how for a very small dataset an array is more performant than a hashmap because iterating through a small number of elements is quicker than hashing the value to lookup in the map. But most of the time things like that are micro-optimizations that are done way after the project has launched and you've found a bottleneck and have tried, tested, and profiled the potential optimizations and made an informed decision