package com.txq.test;
public class BinarySearch {
public int binarySearch(int []arr,int key){
return binarySearch(arr,0,arr.length-1,key);
}
private int binarySearch(int[] arr, int left, int right, int key) {
int mid = (left + right) / 2;
if (arr[mid] == key) return mid;
if (left <= right) {
if(Math.abs(arr[left] - arr[mid-1]) == (mid - 1 - left)){//左边连续
if((key >= arr[left] && key < arr[mid]) ||(key <= arr[left] && key > arr[mid])){
return binarySearch(arr,left,mid-1,key);
} else {
return binarySearch(arr,mid+1,right,key);
}
} else {//右边连续
if((key >= arr[right] && key < arr[mid]) ||(key <= arr[right] && key > arr[mid])){
return binarySearch(arr,mid+1,right,key);
} else {
return binarySearch(arr,left,mid-1,key);
}
}
}
return -1;
}
}