There are many ways of implementing an algorithm of binary search on a sorted list. I want to share how I tackle the problem,
Problem
Given a sorted list, find whether a target number is in the list or not. For example, you want to find whether the number
5
is in the list of[1,2,3,4,5,6,7,8,9,10]
Here is my intuition of the problem
- Since the list of already sorted, have two pointers
left
andright
- Calculate the middle index of
left
andright
bymid = left + (right — left) / 2
. Note that I did not calculate it bymid = (left + right) / 2
.This is to cover the case whereleft + right
is bigger than the maximum value ofInteger
in Java therefore it becomes a negative number. (For example,Integer.MAX_VALUE + 1
becomes-2147483648
which isInteger.MIN_VALUE
) - Compare the target number
target
with the number on the middle index,num
until you find the target or reach the end,(left > right)
if target == num
, return trueelse if (target < num)
, it meanstarget
can only exist on the left side of themid
, and therefore we assignright = mid — 1
else // (target > num)
, it meanstarget
can only exist on the right side of themid
, so we assignleft = mid + 1
Below is my sample code. Any comment or upvote is appreciated!