【发布时间】:2011-04-30 08:20:03
【问题描述】:
嘿,我被要求为我在大学的数据结构课程编写递归二进制搜索,但我遇到了一个小问题。当我搜索超出范围的数字(在这种情况下超过 10)时,它会引发超出范围的异常。我理解它为什么这样做,因为数组没有> 10个空格,但我不知道如何解决它。有任何想法吗?
我搜索的数组是有序数组 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);
}
【问题讨论】:
-
二分搜索不应该使用 / 2 它应该使用按位 >>.
-
为什么?你不在乎这些比特长什么样。您关心数字是多少(以及它的一半是多少)。这种类型的优化应该留给编译器/jvm。
标签: java search recursion binary