Here is an example how to recursively invert the order of a string or an array in Java.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package pt.joaobrito; public class Recursive { /** * The main method * * @param args */ public static void main(String[] args) { System.out.println("Inverted string: " + reverseString("123456789")); System.out.print("Inverted array: "); int[] ra = reverseArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}); for (int s : ra) { System.out.print(s); } System.out.println(""); } /** * This method inverts the order of the string * * @param s * @return the reverse string */ public static String reverseString(String s) { if (s.length() == 0) { return s; } // recursive call return s.substring(s.length() - 1) + reverseString(s.substring(0, s.length() - 1)); } /** * This method inverts the order of the array * * @param array * @return the inverted array */ public static int[] reverseArray(int[] array) { if (array.length <= 1) { // stop condition return new int[]{}; } int[] aux = new int[array.length - 2]; for (int i = 0; i < aux.length; i++) { aux[i] = array[i + 1]; } int[] g = reverseArray(aux); // recursive call System.arraycopy(g, 0, array, 1, g.length); int firstPosition = array[0]; array[0] = array[array.length - 1]; array[array.length - 1] = firstPosition; return array; } } |
The output is:
Notice that in the string method we have twice the iterations that we have in the array method, because we go through all positions in the string.
If you know other ways of doing it, please feel free to comment it out.
Thanks.
