There are numerous ways to reverse an array and they are the following:
Additional array method
In this method, we declare an auxiliary array of the same size as the original array. We will then start iterating over the original array in reverse order and starting to fill the additional array from the beginning.
Let us consider the following program that reverses an array:
Source Code:
import java.util.*; classHelloWorld { // function that reverses array and stores it // in another array staticvoidreverseTheArray(int arr[], int n) { // Declare an auxiliary array int[] auxiliary = newint[n]; int j = n; for (int i = 0; i < n; i++) { // Fill the auxiliary array auxiliary[j - 1] = arr[i]; j = j - 1; } // printing the reversed array System.out.println("The array is:"); for (int i = 0; i < n; i++) { System.out.println(auxiliary[i]); } } publicstaticvoidmain(String[] args) { // Initialize an array int [] arr = {10, 20, 30, 40, 50}; reverseTheArray(arr, arr.length); } }
In this method, we initialize two variables left and right as 0 and N - 1 respectively and start swapping elements by incrementing and decrementing the variables by one respectively.
Let us consider the following program that reverses an array:
Source Code:
class HelloWorld { public static void main(String[] args) { // Initialize an array int[] arr = {10, 20, 30, 40, 50}; // Initialize two variable // to traverse the array int left = 0, right = 4; // Iterate till left is // lesser than right while(left < right) { // Swap values int third = arr[left]; arr[left] = arr[right]; arr[right] = third; left++; right--; } // Print array elements System.out.println("The array elements are:"); for(int index = 0 ; index < 5 ; index++) { System.out.println(arr[index]); } } }
Output:
Output Description:
As you can see in the output the array has been reversed.
In this tutorial, we discussed different ways to reverse an array in Java. We believe this tutorial has surely helped you to enhance your knowledge in your field of you.