我对二进制搜索的概念相当陌生,并且正在尝试编写一个在 Java 中执行此操作的程序以供个人练习。我很好地理解了这个概念,但我的代码不起作用。
我的代码中发生了一个运行时异常,导致 Eclipse,然后是我的计算机崩溃……不过,这里没有编译时错误。
这是我到目前为止所拥有的:
public class BinarySearch
{
// instance variables
int[] arr;
int iterations;
// constructor
public BinarySearch(int[] arr)
{
this.arr = arr;
iterations = 0;
}
// instance method
public int findTarget(int targ, int[] sorted)
{
int firstIndex = 1;
int lastIndex = sorted.length;
int middleIndex = (firstIndex + lastIndex) / 2;
int result = sorted[middleIndex - 1];
while(result != targ)
{
if(result > targ)
{
firstIndex = middleIndex + 1;
middleIndex = (firstIndex + lastIndex) / 2;
result = sorted[middleIndex - 1];
iterations++;
}
else
{
lastIndex = middleIndex + 1;
middleIndex = (firstIndex + lastIndex) / 2;
result = sorted[middleIndex - 1];
iterations++;
}
}
return result;
}
// main method
public static void main(String[] args)
{
int[] sortedArr = new int[]
{
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29
};
BinarySearch obj = new BinarySearch(sortedArr);
int target = sortedArr[8];
int result = obj.findTarget(target, sortedArr);
System.out.println("The original target was -- " + target + ".\n" +
"The result found was -- " + result + ".\n" +
"This took " + obj.iterations + " iterations to find.");
} // end of main method
} // end of class BinarySearch