[英]Java recursive binary search throwing out of bounds exception?
嘿,有人要求我為大學的數據結構課寫一個遞歸二進制搜索,但是我有一個小問題。 當我搜索超出范圍的數字(在這種情況下超過10)時,將拋出超出范圍的異常。 我知道為什么這樣做,因為數組沒有> 10個空格,但是我不知道如何解決它。 有任何想法嗎?
im搜索的數組是有序數組1-10(索引0-9)。
public int recursiveBinarySearch(int[] anArray, int searchedNumber, int min, int max) {
if (min > max)
{
System.out.println(searchedNumber + " is not present in tha array.");
//return -1 to show that the value has not been found
return -1;
}
// find the centre of the array
int centre = (min + max) / 2;
if (anArray[centre] == searchedNumber)
{
System.out.println(searchedNumber + " was found at index " + centre);
return centre;
}
if (anArray[centre] < searchedNumber)
{
return recursiveBinarySearch(anArray, searchedNumber, centre+1, max);
}
return recursiveBinarySearch(anArray, searchedNumber, min, centre-1);
}
public int recursiveBinarySearch(...) {
if (max >= array.length) {
max = array.length - 1;
}
if (min < 0) {
min = 0;
}
... rest of the code
}
附注:不要太誇張,但我也建議使用一致的縮進。 相信我,它在編寫無錯誤程序方面大有幫助。
我想它以min = 0
和max = 9
,然后
min = 0, max = 9, c = (0+9 / 2) = 4
min = 5, max = 9, c = (6+9 / 2) = 7
min = 8, max = 9, c = (8+9 / 2) = 8
min = 9, max = 9, c = (9+9 / 2) = 9
min = 10, max = 9, ...
如您所見, min = 10
當然會引起問題。 為了避免這種情況,請擴大初始條件:
if (min > max || min > Array.length -1 || max < 0)
// not found!
因此,如果您在兩個方向中的任何一個方向上遍歷數組,那么都不會找到請求的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.