二进制搜索错误

时间:2016-04-20 21:08:56

标签: java binary-search

我正在尝试对一个数字数组中的方法进行二进制搜索,每个数字随机填充0到100。我正在搜索数组中的数字但是在运行程序时我遇到了多个错误。

public static void binarySearch(int[] array){
  Arrays.sort(array);
  int searchComparisons = 0;
  int lower = array[0];
  int upper = array[array.length - 1];

  for (int i = 0; i<array.length; i++){
    System.out.println("Element "+i+" is " +array[i]);
  }

  int testSubject = (array[0]+array[array.length-1])/2;

  while((array[testSubject] != 99) && (lower <= upper)){
  searchComparisons++;
    if (array[testSubject] > 99){                                              
              upper = testSubject - 1;   
         }                                                                
              else{                                                        
          lower = testSubject + 1;    
    }
       testSubject = (lower + upper) / 2;
     }

     if (lower <= upper){
           System.out.println("Binary search - number of comparisons "   +searchComparisons);
           System.out.println("This index = "+testSubject);
     }
     else{
          System.out.println("Linear search - number of commparisons: " +searchComparisons);
          System.out.println("Number not found");
  }

}

错误是:

java.lang.ArrayIndexOutOfBoundsException: 50
    at SearchArray.binarySearch(SearchArray.java:49)
    at SearchArray.main(SearchArray.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
  

0 个答案:

没有答案