0 0
WP Ad Inserter plugin
Read Time:9 Minute, 38 Second

Table of Contents

When programmers process arrays starting with the last element, it is always more efficient to reverse the array so that the first element is placed at the array’s last position. Then, the second element is at the array’s second last position until the last element is at the first index.

One of Java’s Crucial Operations is reversing an array. It is a common array-based coding challenge that programmers frequently pose during the first few rounds of interviews to determine whether or not they can code. You can solve this problem in several ways, and we’ll look at the most frequent ones in Java. Because it isn’t focused on data types, this approach works with any sort of array, including string and integer arrays and object arrays.

The first approach for reversing an array is to do so in a brute force way, without requiring additional data structures or library methods. Yes, you can also reverse the array by developing your function that goes through the array and swaps elements until the array is sorted. That is the best way to approach coding interviews.

Reverse an array in Java

In Java, there are several ways to reverse an array. These are the following:

  • Using Collections.reverse() method
  • Reverse an Array Using a For Loop
  • Using StringBuilder.append() method
  • In-place array reversal
  • Using Swapping
  • Using ArrayUtils.reverse()

Printing an Array in Backwards Order

If we wish to print the array in reverse order without reversing it, we can do so by using a for loop that starts writing from the end of the array. It is an excellent solution if we only want to print the array in reverse order without processing.

SUGGESTED READ

The array is printed in reverse order in the following software.

import java.util.*;
import java.util.stream.*;
public class Codeunderscored
{ public static void main(String[] args) { Integer[] intVars = {10,20,30,40,50,60,70,80,90}; // start from the first element when printing the array System.out.println("The initial Array:"); for(int i=0;i<intVars .length;i++) System.out.print(intVars[i] + " "); System.out.println(); //start from the last element when printing the array System.out.println("The initial Array in a reversed order:"); for(int i=intVars .length-1;i>=0;i--) System.out.print(intVars[i] + " "); }
}

It is a viable alternative for printing the array simply. Java has several methods for reversing the indices of elements in an array. The many ways that we will go through in-depth in this tutorial are given below.

  • Making use of the ArrayList reverse method
  • Looping with the usual method
  • Using reversal in-place

Using Collections.reverse() method: ArrayList is used to reverse an array

The ‘reverse’ method in the collections framework is used to reverse an array in Java.

However, because the ‘reverse’ method accepts a list as an argument, you must first convert an array to a list. The ‘reverse’ technique is used in the following application to reverse an array.

import java.util.*; public class Codeunderscored { /*function reverses the elements of the array*/ static void reverse(Integer numArray[]) { Collections.reverse(Arrays.asList(numArray)); System.out.println("The resultant Reversed Array is:" + Arrays.asList(numArray)); } public static void main(String[] args) { Integer [] numArray = {11,13,15,17,19}; System.out.println("The resultant original Array:" + Arrays.asList(numArray)); reverse(numArray); }
}

We utilize the reverse function in this program on an array to convert it to a list. Further, we may reverse a string array similarly, as illustrated in the following example.

SUGGESTED READ

import java.util.*; public class Codeunderscored { /*function reverses the elements of the array*/ static void reverse(String arrVar[]) { Collections.reverse(Arrays.asList(myArray)); System.out.println("The resultant reversed Array:" + Arrays.asList(arrVar)); } public static void main(String[] args) { String [] arrVar = {"apple", "mangoes", "banana", "lemon", "quava", "peas","passion"}; System.out.println("The resultant original Array:" + Arrays.asList(arrVar)); reverse(arrVar); }
}

The software above creates a string array. We reverse the array by changing it to a list and invoking the reverse function on it.

How to reverse an array using a For Loop

Another method of reversing an array is to create a new array and reverse the elements of the previous array. Take a look at the following example.

public class Codeunderscored { static void ReverseArray(char charArray[], int n) { char[] finalArray = new char[n]; int j = n; for (int i = 0; i < n; i++) { finalArray[j - 1] = charArray[i]; j = j - 1; } System.out.println("The resultant Reversed array: "); for (int k = 0; k < n; k++) { System.out.print(finalArray[k] + " "); } } public static void main(String[] args) { char [] char_array = {'C','O','D','I','N','G'}; System.out.println(" The initial array is : "); for (int k = 0; k <charArray .length; k++) { System.out.print(charArray[k] + " "); } System.out.println(); ReverseArray(charArray, charArray.length); }
}

As an example, we’ve utilized a character array. We reverse the array items one by one using the reverse function and then display the reversed array.

Employing the StringBuilder.append() method

If you’re working with a String array, you may use a StringBuilder to attach each array element with a for loop decrementing from the array’s length, convert the StringBuilder to a string, and divide it back into an array as a fourth method.

// Program for array reversal using the StringBuilder import java.util.Arrays; class Codeunderscored { public static void main (String[] args) { String[] arr = {"Code", "Underscored"}; StringBuilder reverseArray = new StringBuilder(); for (int i = arr.length; i > 0; i--) { reverseArray.append(arr[i - 1]).append(" "); }; String[] finalArray = reverseArray.toString().split(" "); System.out.println(Arrays.toString(finalArray)); }
}

In-place array reversal

Reversing the elements of an array in-place without utilizing a separate array is the third way of array reversal. The array’s initial component is swapped with the last element of the array in this function. Similarly, the array’s second element is exchanged with the array’s second last element, and so on. We’ll have the full array inverted at the end of the array traversal. In-place array reversal is demonstrated in the following program.

SUGGESTED READ

import java.util.Arrays;
public class Codeunderscored { /*Swap the first element of the array with the last element, the second element with the second-to-last element, etc.
*/ static void reverseArray(arrVar[], int size) { int i, k, temp; for (i = 0; i < size / 2; i++) { temp = arrVar[i]; arrVar[i] = arrVar[size - i - 1]; arrVar[size - i - 1] = temp; } /*printing the resulting reversed array*/ System.out.println("The resultant reversed Array is: n" + Arrays.toString(arrVar)); } public static void main(String[] args) { int [] numArray = {21,32,43,54,55,76,87,98,109}; //original array printing System.out.println("Original Array: n" + Arrays.toString(numArray)); //function for calling the reverse array reverseArray(numArray, numArray.length); }
}

The software generates a reversed array by swapping the elements in the original array without using the second array, as seen in the output. This method is more efficient because it uses less memory.

Putting Swapping to Work

The array is input and printed in the second procedure using a similar technique. However, unlike the previous way, we do not build a new array. Instead, we invert the array’s original order.

The array’s elements are swapped in this procedure. The first and last elements are switched around. The second element replaces the last but one element, and so on. Take, for example, the array [1, 2, 3,…., n-2, n-1, n]. We change 1 to n, 2 to n-1, 3 to n-2, and so on.

// Program for reversing the array in a fewer number of swaps public class arrayReverse { // function swaps the array's first element with last // element, second element with last second element and // so on static void reverse(int numArray[], int n) { int j, w, x; for (j = 0; j < n / 2; j++) { x = numArray[j]; numArray[j] = numArray[n - j - 1]; numArray[n - j - 1] = x; } // printing the reversed array System.out.println(" The resultant reversed array is: n"); for (w = 0; w < n; w++) { System.out.println(numArray[w]); } } public static void main(String[] args) { int[] arrVars = { 50, 70, 80, 90, 100 }; reverse(arrVars, arrVars.length); }
}

Using ArrayUtils.reverse()

Apache Commons is an open-source library containing many utility libraries required for Java software development. This library should be included by default in Java projects to complement JDK. Apache commons-lang provides an ArrayUtils class with overloaded reverse() methods to reverse int, float, or object arrays in Java. This method also reverses the given array in place rather than returning a new one.

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils; /** * Program for reversing an array in Java using Apache Commons Lang ArrayUtils * class. * */
public class Pattern { public static void main(String args[]) { String[] compVars = {"HP", "DELL", "IBM", "Lenovo"}; System.out.println(" Original Array before reversal: " + Arrays.toString(compVars)); ArrayUtils.reverse(compVars); System.out.println("Resultant Array after reversal: " + Arrays.toString(compVars)); } }

As you can see, we’ve successfully reversed the array with just one line. You must include commons-lang3-3.4.jar in your application’s classpath to use the ArrayUtils class from Apache commons-lang. You can use Maven instead by having the following dependency in your pom.xml file.

SUGGESTED READ

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version>
</dependency>

Example 1: Program for array reversal using Java Collections

import java.util.*; public class reversingArray { // function responsible for reversing the elements of the array static void reverse(Integer numArr[]) { Collections.reverse(Arrays.asList(numArr)); System.out.println(Arrays.asList(numArr)); } public static void main(String[] args) { Integer [] numArr = {60, 70, 80, 90, 100}; reverse(numArr); }
}

Example 2 : Program that reverses an array

public class reverseArray { // function responsible for reversing an array and storing it in another array static void reverse(int arrVar[], int n) { int[] bArr = new int[n]; int j = n; for (int i = 0; i < n; i++) { bArr[j - 1] = arrVar[i]; j = j - 1; } // reversed array printing System.out.println("The resultant reversed array is: n"); for (int x = 0; x < n; x++) { System.out.println(bArr[x]); } } public static void main(String[] args) { int [] arr = {10, 20, 30, 40, 50}; reverse(arr, arr.length); }
}

Conclusion

Arrays are a common coding technique for storing several values of the same kind in a single variable. There are various reasons why a programmer might want to reverse an array. When the logic of an issue requires starting from the last entry, it may be necessary to reverse an array.

This article looked at how to reverse an array in Java using several techniques. Though we utilized integer data for demonstration purposes, the same methods are used to reverse the array with any other data, whether primitives or non-primitives.

For specific routines in Java, the most primitive types of arrays — int, long, string, and double – can be inverted. ArrayUtils is a class in Apache commons-lang, an open-source library maintained by the Apache Software Foundation. Toying with the object and basic arrays in Java, this intriguing class is used in conjunction with the java.util.Arrays class. The API includes overloaded methods for reversing many types of Java arrays, including int, long, double, float, and object arrays.

Source: https://www.codeunderscored.com/reverse-an-array-in-java-explained-with-examples/

Previous post How to convert Array to List in Java
How to use the Glob function to find files recursively in Python Next post How to use the Glob function to find files recursively in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.