Problem statement: You are given a sorted array of integers and a target, your task is to search for the target in the given array. Assume the given array does not contain any duplicate numbers.


1. Iterative Implementation


We will use a couple of pointers i.e. low and high to apply binary search. Initially, the low pointer should point to the first index and the high pointer should point to the last index.

Search space: The entire area between the low and the high pointer(including them) is considered the search space. Here, the search space is sorted.

Algorithm:

Now, we will apply the binary search algorithm in the given array:

The above steps will continue until either we found the target or the search space becomes invalid i.e. high < low. By definition of search space, it will lose its existence if the high pointer is appearing before the low pointer.

Dry-run:

Note: If the target is not present in the array, low and high will cross each other.

Note: For a better understanding, please watch the video at the bottom of the page.

Iterative implementation: