使用二分法查找String[] 里面的某一元素位置索引
我尝试用以下方法去确定某一个String对象在数组中的位置索引,但是不管尝试其中哪一个数组元素,输出结果都是-1,请论坛的大神帮忙看看程序的问题,以下写的程序,先提前谢谢各位!
程序代码:public class BinarySearchTest03 {
public static void main(String[] args) {
String[] eg = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
System.out.println(binarySearch(eg,"two"));
}
public static int binarySearch(String[] Strings, String target) {
int min = 0;
int max = Strings.length - 1;
while(min < max) {
int mid = (max + min)/2;
int compare = Strings[mid].compareTo(target);
if(compare == 0) {
return mid;
}else if(compare < 0) {
min = mid + 1;
}else {
max = mid - 1;
}
}
return -1;
}
}







