Search in a rotated sorted array
Binary search still works, because after any rotation at least one half is still sorted. Compare the ends to find which, then check whether the target falls inside that half's range: if it does, search there; if not, search the other. Still O(log n).
Overview
Why binary search survives rotation
A rotation splits the array into two sorted runs. Wherever mid lands, it is inside one of them — so at least one of [lo, mid] and [mid, hi] is entirely in order. That is the invariant the whole solution rests on, and it holds for any rotation amount including zero.
values[lo] <= values[mid] identifies which. Use <=, not <: when lo == mid the left half is a single element and is trivially sorted.
Step through it
What to watch
- One side of
midis always in order. - The decision is about the sorted half's range, not about mid alone.
- The window halves every step, exactly as in plain binary search.
Say this out loud
"One half is always sorted - compare a[lo] with a[mid] to see which. Then check if the target is inside that sorted half's range and discard accordingly. O(log n), no pre-pass to find the pivot."