face, faces, dialogue @ Pixabay

Binary searches are an efficient way to find a particular value in a sorted array. They work by comparing the search target against the middle element of the array. If it’s greater than or equal, then we know that it’s not on our list and so we can stop searching.

Similarly, if it is less than then we know that it must be somewhere before __ in our list and so we need to continue looking for it from there.

ball, binary, computer data @ Pixabay

In this blog post, I will show you how binary searches work with code examples! The code examples below will show you how to use a binary search. The first example will iterate over the array and check if it is equal to our target value, however, this can be very slow as we might have to go through every element in the list looking for __.

In contrast, with a binary search, we only need to look at two elements: the middle one and either of its neighbours (either before or after).

If it turns out that they are not what we’re looking for then there’s no point in continuing checking them because neither of these could possibly lead us any closer than where we stand now!

So all together this means that a linear lookup time becomes logarithmic when using binary searches.


Please enter your comment!
Please enter your name here