注册 登录
编程论坛 JAVA论坛

使用二分法查找String[] 里面的某一元素位置索引

mudi 发布于 2018-12-19 15:42, 2121 次点击
我尝试用以下方法去确定某一个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;
   }
}


2 回复
#2
林月儿2018-12-19 19:35
       public static void main(String[] args) {
           String[] eg = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
           Arrays.sort(eg);
           
System.out.println(Arrays.toString(eg));
           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;
       }
#3
mudi2018-12-21 20:07
回复 2楼 林月儿
thanks very much~~,版主非常感谢。原来是没有先给数组排序造成的。谢谢!
1