Java - Translate the following in-place reverse function from iterative to recur
ID: 3688141 • Letter: J
Question
Java - Translate the following in-place reverse function from iterative to recursive. You should write a helper method. You may not use any "fields" to solve this problem (a field is a variable that is declared "outside" of the function declaration --- either before or after).
public static void reverseI (double[] a) {
int hi = a.length - 1;
int lo = 0;
while (lo < hi) {
double loVal = a[lo];
double hiVal = a[hi];
a[hi] = loVal;
a[lo] = hiVal;
lo = lo + 1;
hi = hi - 1;
}
}
Explanation / Answer
Full Program.
import java.util.*;
import java.lang.*;
import java.io.*;
class Reverse{
static void reverse(char s[],int i,int j){
char c;
c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
if(i < j){
reverse(s,i,j);}
else
System.out.println(s);
}
public static void main (String[] args) throws java.lang.Exception
{
String s = "foo bar baz";
System.out.println(s);
reverse(s.toCharArray(),0,s.length()-1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.