Java代码:
public class binarySearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arr={1,4,6,9,13,2,98};
int low = 0;
int high = arr.length-1;
int key = 98;
System.out.println(solution(arr,low,high,key));
}
private static int solution(int [] arr,int low,int high,int key){
if(low<=high){
int mid = low +(high-low)/2;
if(key==arr[mid]){
return mid;
}
else if(key<arr[mid]){
return solution(arr,low,mid-1,key);
}
else{
return solution(arr,mid+1,high,key);
}
}
return -1;
}
}
输出:6