歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 二分查找改進版

二分查找改進版

日期:2017/3/1 9:51:51   编辑:Linux編程

以下是一段稍改進過的二分查找代碼,即增加一段最大最小值提前判斷的代碼。

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);

}
}

Copyright © Linux教程網 All Rights Reserved