Reputation: 145
So this entire time I thought that my issue with recursion was understanding cases. It turns out that my problem is understanding the values of recursive cases. For example, printing a portion of an array backwards.
Original try
public static void printBackwards(int i, int j, char[] A){
if(i == j){
System.out.println(A[i]);
}
else{
printBackwards(i+1,j,A);
}
}
A working attempt
public static boolean printBackwards(int i, int j, char[] A){
if(i == j){
System.out.println(A[i]);
return true;
}
else{
if(printBackwards(i+1,j,A) == true){
System.out.println(A[i]);
return true;
}
else{
printBackwards(i+1,j,A);
}
}
return false;
}
However, is this even efficient recursion? Or is there a better way through it? This is the only way I could figure out when I looked it it from writing it out.
Upvotes: 2
Views: 137
Reputation: 3456
For my opinion, to solve this problem doesn't need to use recursion. You can just do it with simple loop.
public class PrintBackwards {
public static void main(String[] args) {
char[] a = new char[] {'A', 'B', 'C', 'D'};
for(int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}
}
}
Is there any reason behind this why you use recursion? If not, more faster to do it like example above.
If you want to use recursion, I hope this example can make you understand easier than yours.
public class PrintBackwards {
private static char[] a = new char[]{'A', 'B', 'C', 'D'};
public static void main(String[] args) {
printBackwards(0);
}
public static void printBackwards(int i) {
if (i < a.length) {
printBackwards(++i);
System.out.println(a[i - 1]);
}
}
}
Upvotes: 2
Reputation: 470
Here's the Java code to print array in reverse order:
public class TestProgram {
private int[] a = {4, 2, 7, 1, 9, 5, 8};
public static void main(String[] args) {
TestProgram p = new TestProgram();
p.print(a.length - 1);
}
public void print(int i) {
// the anchor of the recursive method
// it indicates that we are done printing array
if (i < 0)
return;
// print the current value
System.out.printf("%d ", a[i]);
// recursively call print() method
print(i - 1);
}
}
Upvotes: 1
Reputation: 49920
Start by asking "When can I solve the problem right away (w/o a recursive call)?". In this case, it would be when the area has only one element -- that's your base case.
When that ISN'T true, you need to break the problem into making a smaller version (which can be solved by calling printBackwards) and whatever remains to completing the problem. You already have a call that will print A[i+1..j] (for the original value of i). Thus, all that remains is to print A[i]. Figure out if it should be printed before or after the rest of the array, and you're all set.
Upvotes: 1