[英]Binary Search (Java) exception on 5th element
当我制作一个由5个元素组成的数组并搜索第5个元素时,binarySearch方法将返回ArrayOutOfBounds异常。 所有其他测试用例最多可以工作10个元素。
即使我使用了if-else循环,也遇到了此错误。 有人有解释和解决方案吗?
private static int[] arrayEntry() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int size = scan.nextInt();
int[] arr = new int[size];
System.out.println("Enter the items of the array: ");
for(int i=0; i<size; i++){
arr[i] = scan.nextInt();
}
return arr;
}
//code for choice menu
case 2:
Arrays.sort(arr);
System.out.println("Enter the item to be searched: ");
searchItem = scan.nextInt();
int result = binarySearch(arr, searchItem);
if (result!=-1){
System.out.println("Item found at index: "+ result+ " (index starting at 0).");
}else System.out.println("Item not found!");
break;
private static int binarySearch(int[] arr, int searchItem) {
int lastItem = arr.length-1;
int startItem = 0;
while(startItem<=lastItem){
int midValue = startItem + (lastItem-1)/2;
if (searchItem == arr[midValue]){
return midValue;
}
if (searchItem>arr[midValue]){
startItem = midValue+1;
}else lastItem = midValue-1;
}return -1;
}
}
尝试这个
public int runBinarySearchIteratively(
int[] sortedArray, int key, int low, int high) {
int index = Integer.MAX_VALUE;
while (low <= high) {
int mid = (low + high) / 2;
if (sortedArray[mid] < key) {
low = mid + 1;
} else if (sortedArray[mid] > key) {
high = mid - 1;
} else if (sortedArray[mid] == key) {
index = mid;
break;
}
}
return index;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.