이 메서드가 ArrayIndexOutOfBounds 예외를 throw하는 이유를 알지 못합니다.binarySearch 메서드 Throwing ArrayIndexOutOfBounds 예외 - Java
When I change the initial "high"
값을 "int high = array.length - 1;"
으로 변경하면 프로그램에서 return any integer value
을 검색합니다.
내가 뭘 잘못하고 있니?
미리 감사드립니다.
public class BinarySearch {
public static void main(String[] args) {
int searchValue = 12;
int[] givenNums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
binarySearch(givenNums, searchValue);
System.out.println("\nResult: " + searchValue);
}
public static int binarySearch(int[] array, int key) {
int low = 0;
int high = array.length;
int mid = (low + high)/2;
int i = 0;
System.out.println();
while (low <= high) {
System.out.print(i + " ");
if (array[mid] < key) {
low = mid + 1;
mid = (low + high)/2;
} else if (array[mid] > key) {
high = mid - 1;
mid = (low + high)/2;
}
else
return mid;
i++;
}
return -1;
}
}
이다 편곡 당신 * 단지 * 게시 [아주 비슷한 질문] (http://stackoverflow.com/questions/12827289/ ARR입니다 binarysearch-method-throwing-arrayindexoutofbounds-exception-java). 당신은 이미이 에러가 발생하는 이유를 이미 들었습니다 : 당신은'array.length'로 높게 설정할 수 없습니다. 코드가 완료까지 실행되지 않으면 올바른 대답을 생성하지 못하는 것보다 바람직하지 않습니다 (적어도이 경우는 아님). 'array.length - 1' 대신에'array.length'를'high '로 설정하면 아무 것도 고치지 않고, 단지 상황을 악화시킬뿐입니다. – NullUserException
@ user1735982 .. 내 게시물을보고 정확하게 무엇을하는지 이해하십시오 .. –
다른 방법, 다른 문제. –