Medium Searching

Binary Search on a Rotated Array

Receives an array of integers that was sorted in ascending order and then rotated at an unknown pivot (e.g. [4,5,6,7,0,1,2]), plus a target value. At each step it looks at the middle element and first figures out which half of the current range — left or right — is still contiguously sorted by comparing the boundary values; then it checks whether the target falls inside that sorted half's value range to decide whether to keep searching there or move to the other half, halving the range each step. Returns the index (position) where the target is found, or -1 if it is not present.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References