对于 java 字符串数组(例如String[] a
)上的经典 binarySearch,调用搜索方法的正确方法是什么?是吗
binarySearch(a,key,0,a.length)
或者
binarySearch(a,key,0,a.length-1)
我为下面的实现尝试了两种方法,并且似乎都有效.. 是否存在这些调用中的任何一个都可能失败的用例?
class BS{
public static int binarySearch(String[] a,String key){
return binarySearch(a,key,0,a.length);
//return binarySearch(a,key,0,a.length-1);
}
public static int binarySearch(String[] a,String key,int lo,int hi) {
if(lo > hi){
return -1;
}
int mid = lo + (hi - lo)/2;
if(less(key,a[mid])){
return binarySearch(a,key,lo,mid-1);
}
else if(less(a[mid],key)){
return binarySearch(a,key,mid+1,hi);
}
else{
return mid;
}
}
private static boolean less(String x,String y){
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
String[] a = {"D","E","F","M","K","I"};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int x = binarySearch(a,"M");
System.out.println("found at :"+x);
}
}