I am practicing my recursion skills as I think I am really weak in this area.
I have written the following Java class whose purpose is to reverse a string but to do it 'in-place' - i.e. no additional arrays. I have two implementations - one iterative and one recursive. Why would I choose one implementation over the other?
Also, does my recursive solution use tail call optimization?
public class TestRecursion {
public static void reverseIter(char[] in) {
int start = 0;
int end = in.length - 1;
while(start < end) {
swap(start, end, in);
start ++;
end--;
}
System.out.println("iteration result: "+in);
}
public static char[] reverseRecur(char[] in, int start, int end) {
if (end < start) return in;
else {
swap(start, end, in);
return reverseRecur(in, ++start, --end);
}
}
private static void swap(int start, int end, char[] input) {
char c1 = input[start];
char c2 = input[end];
input[start] = c2;
input[end] = c1;
}
public static void main(String[] args) {
char[] input = "testy".toCharArray();
reverseIter(input);
char[] input2 = "testy".toCharArray();
char[] out = reverseRecur(input2, 0, input2.length-1);
System.out.println("recursive result: "+out);
}
}
S.o.println()
out ofreverseIter()
intomain()
, not just for consistency withreverseRecur()
, but also because it is a good habit to write functions without side effects whenever possible. – 200_success♦ Jan 13 '14 at 20:31