I haven't found anything with the specific needs of my function to do this, yes, it is for homework.
So I have:
public void reverseArray(int[] x) {
}
Precondition: x.length > 0
The fact that I can't have the function return anything, and the only argument is an array is leaving me stumped.
I've tried using loops along with the recursion, but everything I've tried seems to end up with infinite instances of the function being made.
I've gotten an idea/suggestion to use another function along with this one, but, how to use the original recursively is beyond me at the moment.
Any help is appreciated.
If I were coding this, I would create a temporary array (maybe with one element removed?) for the recursive call and copy elements back into the original array before returning from the function. You will also need to find a base case to terminate the recursion.
Here is the main method:
and here is the recursive function:
//We are just doing an operation here and calling a helper method.
Because this is your homework, I suggest an example :
Given sequence :
1 2 3 4 5 6 7 8 9 10
You can change to :
10 2 3 4 5 6 7 8 9 1
After that:
10 9 3 4 5 6 7 8 2 1
.....
As you see, step by step, the sequence is "better" and the problem is "smaller". So, the problem you should solve to complete is :
1) How to apply recursive call for this method. for the original, the method is :
reverse(int[] a)
. so, after first step, you should create arrayb from a[2] --> a[n-1]
. and using reverse(int[] b)`.2) after reverse
b
, what should we do to reverse a ? Assign values of b again back to a.3) stop condition : what stop condition ? You see that elements of array b less than elements of array a. So, to which step, we should stop ?
Hope this help :)
Test:
Recursive, O(n), no temporary Array needed.