It’s been a while since I’ve been writing on the blog, so I’ve decided to start being more active and since it’s been almost 15 years since I’ve studied this in University, it can also be a good refreshment course for me as well as anyone else looking into refreshing their memory or learning.

Binary search is a very useful algorithm, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array.

Binary search is used to find the index of an element in a sorted array, and if the element doesn’t exist, that can be determined efficiently as well. It does it by dividing the input array by half at every step, and after every step, either we have found the index that we are looking for or half of the array can be discarded.

Description

Given a sorted array of integers, return the index of the given key. Return -1 if not found.

Example

Given the following array, if search key is 4, binary search will return 2.

Solutions

There are a couple of ways to solve this problem easily, we can either use a recursive or iterative approach, but before we look into both let’s evaluate the complexity for both solutions, and the algorithms for both solutions.

Algorithm

At every step, consider the array between low and high indices

Calculate the middle index.

If element at the middle index is the key, return middle.

If element at middle is greater than the key, then reduce the array size such that high becomes mid - 1. Index at low remains the same.

If element at middle is less than the key, then reduce the array size such that low becomes mid + 1. Index at high remains the same.

When low is greater than high, key doesn’t exist. Return -1.

Recursive

Runtime complexity

Logarithmic, О(logn)

Memory complexity

Logarithmic, О(logn)

The reason why it has O(logn) memory complexity is because it will have to consume memory on the stack.