Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive search for character in array (Java)

Tags:

java

recursion

I was asked to write something that would determine if an array is a subset of another larger array. I've decided to start with a simpler problem and written a function that will determine if a character present in an array of characters. I've came up with this code:

private static boolean findSequenceRecHelper(char [] findIn, char c, int index) {
    boolean result = false;
    if(index<findIn.length) {
        if(findIn[index] == c) {
            result = true;
        }
        else {
            findSequenceRecHelper(findIn,c,index+1);
        }
    }
    return result;
}

I've done some debugging and found that the function iterates through the whole char[] array and when an element in array equals to desired value, result turns to true. But then again it turns to false and false is actually returned, which is incorrect.

I can't find an error here - can someone please help me with this problem.

like image 420
AlM Avatar asked Jan 17 '23 11:01

AlM


1 Answers

In the recursive step:

else
findSequenceRecHelper(findIn,c,index+1);

You should return the value returned by the recursive call. Otherwise - nothing is being done and the recursive call is actually redundant.

private static boolean findSequenceRecHelper(char [] findIn, char c, int index)
{
boolean result = false;
if(index<findIn.length)
{
    if(findIn[index] == c)
        result = true;
    else
    return findSequenceRecHelper(findIn,c,index+1);
    //^ 
    //added return here
}
return result;
}
like image 167
amit Avatar answered Jan 24 '23 18:01

amit