为什么下面的代码返回 -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;
}
}