如何解决递归二分查找列表:“不是语句”?如何?
正在处理一项任务,但我一直遇到错误。我不太擅长 Java,所以我不确定我做错了什么。作业要我评估递归二分查找,我在 binarySearch 方法中发现了错误;它说“列表 = {“1,2,5,7,9,15”};”是表达式的非法开始,而不是语句,并且 ';'即使显然有一个也是预期的。我不知道……我有点压力山大。
方法如下:
//recursive binary search
public boolean binarySearch(int[] list,int target,int low,int high) {
list ={"1,15"};
target = 5;
boolean result = binarySearch(list,target,list.length-1);
executions++;
int mid = (low + high) / 2;
if(!result){
System.out.println("Target not found -- bad search.");
}else{
System.out.println("Target found -- sucessful search!");
}
if (list[mid] == target) {
return true;
} else {
if (low > high) {
return false;
} else {
comparisons++;
if (list[mid] < target) {
return binarySearch(list,mid + 1,high);
} else {
return binarySearch(list,low,mid - 1);
}
}
这里是完整的代码:
public class Problem2 {
public static int executions = 0;
public static int comparisons = 0;
public static int[] numbers = new int[] {1,3,4,6,8,10,11,12,13,14,15,16,17,18,19,20};
public static void main(String[] args) {
System.out.println("2nd fibonacci number: " + fibonacci(2));
System.out.println("Number of executions: " + executions);
System.out.println("Number of comparisons: " + comparisons);
executions = 0;
comparisons = 0;
System.out.println();
System.out.println("Number of operations: " + executions);
System.out.println("Number of comparisons: " + comparisons);
executions = 0;
comparisons = 0;
System.out.println();
System.out.println("Factorial of 7: " + nFactorial(7));
System.out.println("Number of operations: " + executions);
System.out.println("Number of comparisons: " + comparisons);
executions = 0;
comparisons = 0;
}
//recursive Nfactorial
public static int nFactorial(int n) {
comparisons++;
if (n <= 1) {
return 1;
} else {
executions++;
return n * nFactorial(n - 1);
}
}
//recursive fibonacci number
public static int fibonacci(int n) {
comparisons++;
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
executions++;
return fibonacci(n - 1) + fibonacci (n - 2);
}
}
//recursive binary search
public boolean binarySearch(int[] list,mid - 1);
}
}
}
}
}
如果可以,请帮忙。如果您发现其他任何错误,请告诉我。
解决方法
问题
list ={"1,2,5,7,9,15"};
以上是java中初始化int数组的无效语句
修复
使用作为输入传递的数组
注意
初始化数组的正确方法是new int[]{1,15};
一个可能的解决方案
boolean binarySearch(int[] arr,final int left,final int right,final int target) {
if (left > right) {
return false;
}
final int mid = left + (right - left) / 2;
if (arr[mid] == target) { // if matched,return true
return true;
} else if (arr[mid] < target) { // if candidate is less,then more towards right. drag left towards right(i.e: mid + 1)
return binarySearch(arr,mid + 1,right,target);
} else { // else drag right towards left (i.e. mid - 1)
return binarySearch(arr,left,mid - 1,target);
}
}
调用
从主方法调用二分查找方法,带参数
public static void main(String[] args) {
binarySearch(numbers,numbers.length - 1,5); // to find 5
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。