Basic Binary Search

mj park
1 min readFeb 5, 2020

--

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 5is in the list of [1,2,3,4,5,6,7,8,9,10]

Here is my intuition of the problem

  1. Since the list of already sorted, have two pointers left and right
  2. Calculate the middle index of left and right by mid = left + (right — left) / 2 . Note that I did not calculate it by mid = (left + right) / 2 .This is to cover the case where left + right is bigger than the maximum value of Integer in Java therefore it becomes a negative number. (For example, Integer.MAX_VALUE + 1 becomes -2147483648 which is Integer.MIN_VALUE )
  3. 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 true
  • else if (target < num) , it means target can only exist on the left side of the mid , and therefore we assign right = mid — 1
  • else // (target > num) , it means target can only exist on the right side of the mid , so we assign left = mid + 1

Below is my sample code. Any comment or upvote is appreciated!

--

--

mj park
mj park

Written by mj park

Software Engineer | Scala | Functional Programming

No responses yet