Java, recursively reverse an array
Calling reverseArray(0, n, arr) here n is length of array
public void reverseArray(int i, int n, int [] arr)
{
if(i==n)
{
return ;
}
else
{
reverseArray(i+1, n, arr);
System.out.println(arr.at(i));
}
}
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 array b 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 :)
void reverseArray(int[] x){
reverse(x, 0, x.length -1);
}
void reverse(int[] x, int i, int j){
if(i<j){//Swap
int tmp = x[i];
x[i] = x[j];
x[j] = tmp;
reverse(x, ++i, --j);//Recursive
}
}
Test:
int[] s = new int[]{1,2,3,4,5};
reverseArray(s);
System.out.println(Arrays.toString(s));//"5,4,3,2,1"
Recursive, O(n), no temporary Array needed.
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.