以下是一段稍改進過的二分查找代碼,即增加一段最大最小值提前判斷的代碼。
public long binarySearch(long low,long high,String[] data,String key){
if(low > high || key.compareTo(data[low]) < 0 || key.compareTo(data[high]) > 0){
return -1;
} else if(key.compareTo(data[low]) == 0){
return low;
} else if(key.compareTo(data[high]) == 0){
return high;
} else {
long mid = (low+high)/2;
if(key.compareTo(data[mid]) == 0)
return mid;
else if( key.compareTo(data[mid]) > 0)
return binarySearch(mid+1,high,data,key);
else
return binarySearch(low,mid-1,data,key);
}
}