Blog

Article

# Array reverse in Java – Algorithms for interview

There is an array `{1, 2, 3, 4}` and it needs to be expanded (or inverted) to get an array `{4, 3, 2, 1}`.

We find the middle of the `array - array.length / 2`. Iterate over the elements of the array from the beginning to the middle and simultaneously swap the elements with index `i` and `array.length - i - 1`. To exchange values, we use the option with the introduction of a temporary variable, discussed in the previous section.

``````public class ArrayInverter {
public static void invert(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int tmp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] =  tmp;
}
}
}
``````

Please note that there is no `main()` method in the `ArrayInverter` class – we will call the `invert()` method from another class. To call a method located in another class, write the class name – `ArrayInverter.invert(array1)`:

``````import java.util.Arrays;

public class ArrayInverterTest1 {
public static void main(String[] args) {
int[] array1 = new int[]{};
System.out.print(Arrays.toString(array1) + " => ");
ArrayInverter.invert(array1);
System.out.println(Arrays.toString(array1));

array1 = new int[]{0};
System.out.print(Arrays.toString(array1) + " => ");
ArrayInverter.invert(array1);
System.out.println(Arrays.toString(array1));

array1 = new int[]{0, 1};
System.out.print(Arrays.toString(array1) + " => ");
ArrayInverter.invert(array1);
System.out.println(Arrays.toString(array1));

array1 = new int[]{0, 1, 2};
System.out.print(Arrays.toString(array1) + " => ");
ArrayInverter.invert(array1);
System.out.println(Arrays.toString(array1));

array1 = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.print(Arrays.toString(array1) + " => ");
ArrayInverter.invert(array1);
System.out.println(Arrays.toString(array1));
}
}
``````

If we look closely at the code in the `ArrayInverterTest1` class, we can see that one block of code is repeated five times. Duplicate code is a bad practice, so let’s put the duplicate code in a separate method that will be called five times with different values:

Leave an application and get a free consultation from our manager.

• Help in choosing a direction
• Course consultation
• Additional materials for the start
``````import java.util.Arrays;

public class ArrayInverterTest2 {
public static void main(String[] args) {
testInvert(new int[]{});
testInvert(new int[]{0});
testInvert(new int[]{0, 1});
testInvert(new int[]{0, 1, 2, 3, 4});
}

private static void testInvert(int[] array) {
System.out.print(Arrays.toString(array) + " => ");
ArrayInverter.invert(array);
System.out.println(Arrays.toString(array));
}
}
``````
By Alex Kara on Apr 01, 2022