# Binary Search

Welcome to the binary search series! In this series of post we will focus on implementing binary search for coding interviews and some of the common pitfalls that come along. We will start with the most basic implementation of binary search first.

Before we start coding a solution we want to make that we are aware of all the possible pitfalls in our code. Take a look at the test cases below to get a feel for the scenarios we need to be on the look out for.

We want to make sure we handle an empty array correctly, an array that doesn’t have the target we seek, an array with one element, and a few other possible edge cases that could come up. Be sure to read through the test. If we don’t address all these possible edge cases then our solution won’t be correct. The solution below addresses all these concerns.

After taking some time to read and understand how this code works, lets focus on a few critical parts of it.

First lets look at how the variable mid is calculated. An alternative is to calculate it this way

However this method can lead to integer overflows so we don’t do it that way.

Next you my wonder why set

but on the other hand we set

This is because of integer division in java. Integer division is simply always rounding down we you divide. For example 5/2 = 2 in java. However if we rounded up it would be equal to 3. Why does this matter?

Consider the case when we have an array like so [1,2,3] with a target of 4. When we get to the point in our algorithm where l=2 and r=3 if we set l=mid=2+(3-2)/2 then we would have l=2+0=2. As a result we find ourself in an infinite loop because out terminating condition

would never be met. This is because (3-2)/2=0 would never allow our l variable to increment!

I hope you enjoyed this tutorial on basic binary search. In the next post we will add a variation to the typical binary search algorithm because coding interviews usually wont to see that your comfortable enough with these basic algorithms to handle a twist in them.