java - If my recursive method return true, why it enters a recursive call?
问题描述
im working with multi-dim arrays. i wrote a method that uses binary search to see if some int is in one the sub arrays. i debugged the binarySearch it works fine. i debugged the method that calls binarySearch. i saw that it entered the if statment. returned true. but it enters once again into the recursive call.
my code:
int[][] mainArr = {
{1,1,1,1},
{1,2,3,4},
{4,5,6,6},
{6,7,8,9}
};
System.out.println(exerciseSix(mainArr, 5, 0));
}
public static boolean exerciseSix(int[][] arr, int x, int position){
int binAns = -1;
if(position == arr.length){
return false;
}
if(x == arr[position][arr[position].length - 1]){
return true;
}
if(x < arr[position][arr[position].length - 1]){
binAns = binarySearch(arr[position], 0, arr[position].length, x);
}
if(x == binAns){
return true;
}
if(x > arr[position][arr[position].length - 1]){
exerciseSix(arr, x, ++position);
}
return false;
}
static int binarySearch(int[] arr, int l, int r, int x){//l is the left most index
if(r < l)
return -1;
int m = l+(r-l)/2;
if(arr[m] == x)
return arr[m];
if(arr[m] < x)
return binarySearch(arr, m+1, r, x);
return binarySearch(arr, l, m-1, x);
}
解决方案
Could it be that you are not using the value returned? eg in this part:
if(x > arr[position][arr[position].length - 1]){
exerciseSix(arr, x, ++position);
}
return false;
No matter what exerciseSix(arr, x, ++position)
returns it will be thrown away and it hits the next line which is return false
. Earlier in a similar situation you assign the result to a variable, but here you downright discard it making it dead code. If you wanted to return it you need to write return exerciseSix(arr, x, ++position);
since return
only works on level at a time.
推荐阅读
- reactjs - 如何在 React Js 中呈现更新的状态?
- python - 覆盖在不同功能中使用多个 kwargs 的类
- reactjs - 如何使用反应测试库修复错误“HTML元素类型的参数| null不能分配给'TargetElement'类型的参数?
- html - 按钮上的网格纹理
- sql - 外键显示空值 (ssms)
- javascript - 仅在 Angular 应用程序加载完成后才加载 index.html 中定义的外部脚本
- c++ - 如何将 Int 参数输入到 torch::jit::script::Module 的 forward 函数
- javascript - 是否可以将 google map javascript api 缩放级别增加到与 maps.google.com 相同?
- excel - 可变前导零(数字格式)
- amazon-sagemaker - 如何在 sagemaker 中设置 SAGEMAKER_SUBMIT_DIRECTORY 环境变量