public static void main(String[] args) {
int [] arr = {11,14,18,22,36,89,125};
System.out.println(recursive_binary_search(arr,0,arr.length,989));
}
public static int recursive_binary_search(int[] A,int p,int r,int x) {
if( p > r) {
return -1;
}else {
int q=(p+r)/2;
if(A[q]==x) {
return q;
}else if(A[q]>x) {
return recursive_binary_search(A,p,q-1,x);
}else {
return recursive_binary_search(A,q+1,r,x);
}
}
}
Hey, thank you for reading. I am having some problem with this recursive binary search method. When I try to search something that is not in the array, java give me "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7".
I thought it should return -1 because of the p>r condition. I tried to change the condition to p>=r but then it would return -1 for things that are actually present in array. What am I doing wrong? Thank you so much
搜索应从0
到arr.length-1
,
System.out.println(recursive_binary_search(arr,0,arr.length-1,989));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.