Updated answer:
I think I misunderstood. If you have to use the function as declared and just fill in the temp
bit, and you just have to output the array in reverse order (not actually change its contents), then it's simple: Just make temp
a copy of length - 1
characters of the array (perhaps using System.arraycopy
) and pass the new, shorter array into the function. Don't do that if the array you receive is only one character long; that's your recursion termination condition (you always have to have something that stops the recursion, it should be one of the first things you think about when looking at doing something recursively).
Original answer:
It seems to me that an assignment telling you to use the wrong technique for a problem isn't a very useful assignment. There are all kinds of appropriate teaching exercises for recursion; this isn't one of them.
But let's look at the assignment:
The goal of recursion is basically to repeated do something, on a different part of the problem, until you're done with the problem as a whole. The better example would be looping through a tree structure.
So looking at this problem, your goal is to swap characters in an array until the array has been reversed. What's the thing that repeats here? Swapping characters.
So I'd probably do it by having an index I pass into the function, and have the function swap the character at that index with the character at the length - index
location (e.g., swap the first and last, then the second and second-to-last, etc.). Then have it call itself with index + 1
.
All recursion fundamentally must have a "stop" condition: The point at which the function no longer calls itself. In your case, that would be index >= length_of_array / 2
.
Note that I haven't posted code. Writing the code is the purpose of having assignments, of doing the course; it's an important part of learning.