14/07/2021

[Java] Binary search on rotated array

Given an array of unique items, which was sorted and then rotated an unknown number of positions left or right, find whether an element exists in the array in O(logN) time.

We can do a normal binary search, but each time we need to understand where to continue searching.
Given a middle element, either the left or right side will be sorted and the other side not as there will be at least one element whose successor is not in order, unless array is all ascending or mid is the break point.


After checking the middle element, we look at both sides to determine where the item would be and move  in the correct direction:

  • element at floor < element at mid: left side is sorted
if element at floor <= target < element at mid, search there, otherwise search on the right of mid
  • otherwise left side is not sorted
if right side is sorted (element at mid <= element at ceil) AND element at mid < target <= element at ceil we search on right side of mid, otherwise search on left side

You can check my implementation of rotatedBinarySearch on my Gist along with some tests in BinarySearchRotatedJTests.

No comments:

Post a Comment

With great power comes great responsibility