Search code examples
javarecursionreturnlinear-search

Return statement not returning as expected


Why does the code below return -1 instead of arr.length-1? If the find() method is looking for 24, it should return 5, but now it returns -1. It should only return -1 if n is not found in arr.

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;
    }   
}

Solution

  • You are ignoring the value returned by your recursive call.

    You should change

    find( temp, n );
    

    to

    return find( temp, n );