Can someone improve the recursive implementation of indexOf in Java?

I was working on the assignment of summer Java and there was a problem with the recursive implementation of the indexOf method in Java. Here is what I still have:

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 be getting values ​​that are completely wrong, so I can only imagine the problem with incrementing or counting, but isn't my code increasing charPos by +1 every time? Or is it related to ASCII character values?

I was also wondering if the string "charPos = fromPos" is needed at all. Can I just use fromPos throughout my code, or would I break the "missing link is not value"?

+4
source share
3 answers

You could fully use fromPos completely through your code. Java has never been passed by reference, and you don't even change the charPos value.

It is not clear why your final return statement adds charPos to the return value of the recursive call. Why is this not so:

 return rIndexOf(ch, charPos + 1); 

? In the end, suppose he finds him at position 3 - that will return 3, so you do not want to add 2 to 3 in the previous call, then add 1 to 5 and end up with 6 ...

+6
source

This line:

 return charPos + rIndexOf(ch, charPos + 1); 

is erroneous. Let them say that myString is the "sun" and you call rIndexOf(' ', 0); . Then you will receive:

0 + 1 + 2 + 3 instead of 3. Since charPos is incremented every time, and you add it to yourself. You should simply change this line to:

 return rIndexOf(ch, charPos + 1); 
+3
source

Your last line is incorrect, try this?

 return rIndexOf(ch, charPos + 1) 

also, it will create a huge stack in memory, not very efficient.

+2
source

All Articles