我正在做一个使用分治法的程序。不幸的是,我不能使用find(...)
方法。
我不知道该怎么办,而不是在这一行:find(null, 0, 100, 34)
中返回null。
预先谢谢你。
public class Main {
static int find (double T[], int left, int right, double numToSearch) {
if (left <= right) {
int middle = (left + right) / 2;
if (T[middle] == numToSearch) {
return middle;
}
if (T[middle] < numToSearch) {
return find(T, middle+1, right, numToSearch);
}
return find(T, left, middle-1, numToSearch);
}
return -1;
}
public static void main(String[] args) {
System.out.println(find(null /* (OR WHAT HERE TO MAKE IT WORK) */, 0, 100, 34));
}
答案 0 :(得分:0)
您必须提供一个数组,double[]
。另外,您必须使用该数组作为第一个参数和有效的第三个参数(“ right”不得大于数组的最大索引)来调用find(...)
方法。
请参见以下代码,该代码基本上是您的代码以及示例数组,对find
方法的正确调用以及main
方法中的一些(希望是有帮助的)注释:
public class Main {
static int find(double T[], int left, int right, double numToSearch) {
if (left <= right) {
int middle = (left + right) / 2;
if (T[middle] == numToSearch) {
return middle;
}
if (T[middle] < numToSearch) {
return find(T, middle + 1, right, numToSearch);
}
return find(T, left, middle - 1, numToSearch);
}
return -1;
}
public static void main(String[] args) {
// create an array that you can use for searching a number, here it is 34 at index 8
double[] array = {1, 2, 3, 4, 5, 6, 7, 30, 34, 44, 45, 66, 67, 71, 72, 73, 77, 85, 89, 90, 99};
// use the find-method with a valid maximum index (right) and the array defined before
System.out.println(find(array, 0, array.length - 1, 34));
}
}
结果仅为8,所以可能在输出中添加更多信息,如下所示:
public static void main(String[] args) {
// create an array that you can use for searching a number, here it is 34 at index 8
double[] array = {1, 2, 3, 4, 5, 6, 7, 30, 34, 44, 45, 66, 67, 71, 72, 73, 77, 85, 89, 90, 99};
double numberToFind = 34;
// use the find-method with a valid maximum index (right) and the array defined before
System.out.println("The number " + numberToFind + " is at index " + find(array, 0, array.length - 1, 34));
}