二分法的变型题
package Level4;
/**
* 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 class S33 {
public static void main(String[] args) {
int[] A = {2, 3, 4, 5, 6, 0, 1};
System.out.println(search(A, 0));
}
public static int search(int[] A, int target) {
return rec(A, target, 0, A.length-1);
}
// 递归查找
public static int rec(int[] A, int target, int low, int high){
if(low >
high){ // 没找到的情况
return -1;
}
int mid = low + (high-low)/2;
if(A[mid] == target){ // 找到了
return mid;
}
int res = rec(A, target, low, mid-1); // 在左侧查找
if(res == -1){ // 如果左侧没找到,继续在右侧查找
res = rec(A, target, mid+1, high);
}
return res;
}
}