以下是一段稍改进过的二分查找代码,即增加一段最大最小值提前判断的代码。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);
}
}相关阅读:Java针对数组的普通查找法和二分查找法 http://www.linuxidc.com/Linux/2012-03/57065.htm二分查找之Java实现 http://www.linuxidc.com/Linux/2012-05/59869.htm用Python实现二分查找 http://www.linuxidc.com/Linux/2012-12/75948.htm二分查找的实现及注意事项 http://www.linuxidc.com/Linux/2013-07/87308.htm