public class Solution {
public int search(int[] A, int target) {
// Iterative binary search
int left = 0, right = A.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(A[mid] == target) {
return mid;
}
// Compares A[left] and A[mid]
if(A[left] <= A[mid]) { // pivot in (mid, right)
if(A[left] <= target && A[mid] > target) { // target in [left, mid)
right = mid - 1;
} else { // target in (mid, right]
left = mid + 1;
}
} else { // pivot in (left, mid)
if(A[mid] < target && A[right] >= target) { // target in (mid, right]
left = mid + 1;
} else { // target in [left, mid)
right = mid - 1;
}
}
}
return -1;
}
}
Time: O(log(n))
Space: O(1)