我正在尝试构建一个通过排序数组的 binarySearch 方法,并评估给定元素是否作为int 目标给出形式给出)。它将通过评估平均值是大于还是小于目标值来做到这一点,并相应地循环遍历数组的前半部分或后半部分。
我想我有基本的代码,但我遇到了一些问题:
- 整数目标 = 0;(返回真)=> 正确
- int 目标 = (3, 6, 9); (返回 false) => 应该返回 true
- int 目标 = (15, 19, 21, 90); 返回 "java.lang.ArrayIndexOutOfBoundsException: 15" => 应该为真
我想这与我在各自的 if 情况下的 for 语句有关,但我试图调试但不能。另外,我不允许使用库方法。希望这个问题对像我这样的其他初学者有帮助。我认为它探索了一些 Java 概念,如语法、逻辑和基本使用。感谢您的帮助。
public class ArrayUtilities
{
public static void main(String[] args)
{
int[] arrayBeingSearched = {0, 3, 6, 9, 12, 15, 19, 21, 90};
int target = 90;
System.out.println("linear: " + linearSearch(arrayBeingSearched, target));
System.out.println("binary: " + binarySearch(arrayBeingSearched, target));
}
public static boolean binarySearch(int[] arrayBeingSearched, int target)
{
boolean binarySearch = false;
for (int i = 0; i < arrayBeingSearched.length; i++){
int left = 0; //array lower bound
int right = arrayBeingSearched.length - 1; //array upper bound
int middle = ((right - left) / (2)); //array mean
if(arrayBeingSearched[middle] == target){
binarySearch = true;
}
else if(arrayBeingSearched[middle] < target){
for(int j = middle + 1; j < arrayBeingSearched.length - 1; j ++){
int newLeft = arrayBeingSearched[j ++];
if(arrayBeingSearched[newLeft] == target){
binarySearch = true;
break;
}
else{
binarySearch = false;
}
}
}
else if(arrayBeingSearched[middle] > target)
for(int l = 0; l < middle - 1; l ++){
int newRight = arrayBeingSearched[l ++];
if(arrayBeingSearched[newRight] == target){
binarySearch = true;
break;
}
else{
binarySearch = false;
}
}
else{
binarySearch = false;
}
}
return binarySearch;
}
}
好的,根据评论,这会是更好的代表吗?第一条评论主要回答了我的问题,但我只想跟进:
public static boolean binarySearch(int[] array, int target)
{
int start = 0;
int end = array.length - 1;
while (start <= end)
{
int middle = start + (end - start)/2;
if (array[middle] == target) {
return true;
}
else if (array[middle] > target)
{
end = middle - 1;
}
else start = middle + 1;
}
return false;
}
}