二分查找改进版


以下是一段稍改进过的二分查找代码,即增加一段最大最小值提前判断的代码。

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针对数组的普通查找法和二分查找法

二分查找之Java实现

用Python实现二分查找

二分查找的实现及注意事项

相关内容