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
- otherwise left side is not sorted
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