DEV Community

Binary Search

Hajar | هاجر on September 05, 2021

Binary Search is one of the fastest searching algorithms, especially when it comes to searching large (sorted) lists. The main goal of Binary Sear...
Collapse
 
stefnotch profile image
stefnotch

Nice explanation and congratulations on presenting an actually correct variant of binary search. 🚀

Since I believe that anything can be improved, no matter how nice it is, here is some feedback:
Issues

  • No parameters. list and itemToFind should very much be parameters that are passed to the function
  • Usage of parseInt. It's really not needed and it just causes a performance overhead.
  • (start + end) / 2 isn't ideal either, since with large enough arrays, this can cause some overflowing/rounding. The improved variant is start + ((end - start ) / 2) Might be interesting to note
  • An alternative to return -1 is return -start. Then, the negative return value would point at the smallest element that's >= itemToFind. And that's pretty useful when one wants to insert a new element.
Collapse
 
hajarnasr profile image
Hajar | هاجر

Thank you so much for your feedback @stefnotch . 😀
I fixed the no-parameters issue but am curious, why do you think that parseInt isn't needed here? Aren't we using it to avoid having fractions in the middle index? 🤔

Collapse
 
stefnotch profile image
stefnotch

I see, I missed that detail!

Although, parseInt is not designed for that. It's purpose is to turn a string (text) into a number. If the intention is to chop off the fractional part, then Math.floor is the standard function to use.
e.g. start + Math.floor((end - start) / 2)

Collapse
 
aminmansuri profile image
hidden_dude

I like your idea of returning -start.

Collapse
 
segdeha profile image
Andrew Hedges

Great explanation of this kind of search! Nice work, Hajar!

Collapse
 
hajarnasr profile image
Hajar | هاجر

Thank you so much for reading, Andrew. I appreciate it. 🌹

Collapse
 
mahmoudessam profile image
Mahmoud EL-kariouny

thanks :)

Collapse
 
peter_brown_cc2f497ac1175 profile image
Peter Brown

Thank for taking the time to right a legit article instead of all the fluff that so many others produce.

Collapse
 
hajarnasr profile image
Hajar | هاجر

Thank you, Peter. You're so kind. 😊

Collapse
 
hamodey85 profile image
Mohammed Almajid

perfect explanation

Collapse
 
hajarnasr profile image
Hajar | هاجر

Thank you for reading. :)