Tag Archives: array

Reverse String/array recursively

Here is an example how to recursively invert the order of a string or an array in Java.

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:

output

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.