use*_*313 -2 java recursion return linear-search
为什么下面的代码返回-1而不是arr.length-1?如果find()方法查找24,则应返回5,但现在返回-1.如果在arr中找不到n,它应该只返回-1.
public class linearArraySearch {
public static void main(String[] args) {
int[] numbers = new int[]{ 12, 42, 56, 7, 99, 24, 6, 1, 5 };
System.out.println( find(numbers, 24) );
}
public static int find( int[] arr, int n ){
if( arr[arr.length-1] == n ){
return arr.length-1;
}else if( arr.length > 1 && arr[arr.length-1] != n ){
int[] temp = new int[arr.length-1];
for( int i = 0; i < temp.length; i++ ){
temp[i] = arr[i];
}
find( temp, n );
}
return -1;
}
}
Run Code Online (Sandbox Code Playgroud)
您忽略了递归调用返回的值.
你应该改变
find( temp, n );
Run Code Online (Sandbox Code Playgroud)
至
return find( temp, n );
Run Code Online (Sandbox Code Playgroud)