...

/

Invert the Position of Elements in an Array

Invert the Position of Elements in an Array

In this lesson,we will learn how to invert the position of the elements in an array using recursion.

Invert the Position of Elements

Given an array, you must reverse the position of the elements in the array.

Implementing the Code

The following code explains the concept of reversing the elements of an array using recursion.

Experiment with the code by changing the array elements and size to see how the answer changes.

import java.io.*;
class ExampleClass {
private static void invert(int[] array, int currentIndex) {
if (currentIndex < array.length/2) {
// swap array[currentIndex] and array[array.length-1-currentIndex]
int temp = array[currentIndex];
array[currentIndex] = array[array.length-1-currentIndex];
array[array.length-1-currentIndex] = temp;
invert(array, currentIndex+1);
}
}
public static void main(String[] args) {
System.out.println("Before: ");
int[] array = {1,2,3,4,5,6,7};
System.out.print("{ ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("} ");
System.out.println("After: ");
invert(array, 0);
System.out.print("{ ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.print("} ");
}
}

Understanding the Code

The code snippet above can be broken down into two parts: the recursive method and the main where the method is ...