Skip to content

Instantly share code, notes, and snippets.

@bittib
Last active December 9, 2016 07:02
Show Gist options
  • Save bittib/5675990 to your computer and use it in GitHub Desktop.
Save bittib/5675990 to your computer and use it in GitHub Desktop.
Search in rotated sorted array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array.
public int search(int[] A, int target) {
int low = 0, high = A.length-1;
while (low <= high){
int mid = low + (high - low)/2;
if (A[mid] == target)
return mid;
if (A[low] <= A[mid]){
if (A[low] <= target && target < A[mid])
high = mid-1;
else
low = mid+1;
}else if (A[mid] < A[high]){
if (A[mid] < target && target <= A[high])
low = mid+1;
else
high = mid-1;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment