/** * 循环有序的数组进行二分查找 * @param A */ public static int find(int[] A, int n, int target){ if(n<=0) return -1; int left = 0, right = n-1; while(left<=right) { int mid = left + ((right-left)/2); if(A[mid] == target){ return mid; } //转折点在中间点的右半边 if(A[left] <= A[mid]) { if(A[left] <= target && target < A[mid]){ right = mid - 1; } else { left = mid + 1; } } else //转折点在中间点左半边 { if(A[mid] < target && target <= A[right]){ left = mid + 1; } else { right = mid - 1; } } } return -1; }
public static int find(int nums[], int n, int tag) { if (n <= 0) { return -1; } int left = 0; int right = n - 1; int mid = left + ((right - left) / 2); for (; left <= right; ) { if (nums[mid] == tag) { return mid;//输出索引 } //右侧 if (nums[left] <= nums[mid]) { if (nums[left] <= tag && tag < nums[mid]) { right = mid - 1; } else { left = mid + 1; } } else {//左侧 if (nums[right] >= tag && tag > nums[mid]) { left = mid + 1; } else { right = mid - 1; } } } return -1; }