Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone improve the recursive implementation of indexOf in Java?

Tags:

java

recursion

I've been working on a Java summer assignment and there was a problem on recursively implementing the indexOf method in Java. Here is what I have so far:

public int rIndexOf(char ch, int fromPos)
{
    int charPos = fromPos;

    if (charPos >= myString.length() || myString.equals(""))
        return -1;
    else if (myString.charAt(charPos) == ch)
        return charPos;
    else
        return charPos + rIndexOf(ch, charPos + 1);
}

I seem to get values that are completely wrong, so I can only imagine it's a problem with incrementation or counting, but doesn't my code increment charPos by +1 each time? Or does it have to do with ASCII values of characters?

Also I was wondering if the line "charPos = fromPos" was necessary at all. Could I have just used fromPos throughout my code or would that violate the "pass-by reference not value" thing?

like image 320
CowZow Avatar asked Dec 22 '22 09:12

CowZow


1 Answers

You could absolutely have used fromPos all the way through your code. Java never passed by reference, and you're not even changing the value of charPos anyway.

It's unclear why your final return statement adds charPos to the return value of the recursive call. Why isn't it just:

return rIndexOf(ch, charPos + 1);

? After all, suppose it finds it at position 3 - that's going to return 3, so you don't want to add 2 to the 3 in the previous call, then add 1 to the 5 and end up with 6...

like image 127
Jon Skeet Avatar answered Dec 29 '22 00:12

Jon Skeet