Modified binary search

What is modified binary search problem

Given a sorted array of (n) integers that has been rotated an unknown number of times. Give a log(n) algorithm that finds an element in the array. Assume the array has no duplicates.

Modified binary search

Modified binary search algorithm

You need to use a modified binary search method. The trick is to play with the lower and upper array indexes. Binary search in the normal case examines the middle element. If the middle element is equal to the element we are looking for we just return the middle element. If the element that we are looking for is greater than the middle element then we search the right half of the array otherwise we search the left half. This can be accomplished either recursively or by iteration. In our case where the array has been rotated we can not simply search the right or left halves of the array because the order of the elements is not maintained because of the rotation. Consider the following example A = {7, 8, 9, 1, 2, 3, 4, 5, 6} as you can see {7, 8, 9} and {1, 2, 3, 4, 5, 6} are both in order however the transition between the two breaks the order. Let us define some variables:

Notice that no matter how many times we rotate the array we will have one of the following scenarios

The following three cases where x to the left of m

The following three cases where x to the right of m

if none of the above six cases is applied then the array was not rotated. In that case normal binary search can be applied.

Modified binary search in c

Here is a sample code in C++

Please use the comments section below for feedback and questions. Thanks for visiting.

Add a Comment

Your email address will not be published. Required fields are marked *