This guide will explore the process of reversing an array in Java. The task involves taking an integer array as input and reversing the order of its elements. To reverse an array, each element's position should be swapped with its corresponding element from the end. Let's look at some examples to illustrate this concept.
Example 1:
Input:
arr = {1, 2, 3, 4, 5, 6, 7, 8}
Output
arr = {8, 7, 6, 5, 4, 3, 2, 1}
Example 2:
Input:
arr = {4, 8, 3, 9, 0, 1}
Output:
arr = {1, 0, 9, 3, 8, 4}
Approach 1: Using an auxiliary array
One approach is to iterate through the array from the last element to the first, effectively reversing the order, and save each element pointed to by the loop index in a separate array. This new array will now hold the elements of the original array in reverse order. Subsequently, we can output the reversed array to the console. Below is a sample program demonstrating this process.
FileName: ReverseArr.java
public class ReverseArr
{
// method for reversing an array
public int[] reverseArray(int arr[])
{
// computing the size of the array arr
int size = arr.length;
// auxiliary array for reversing the
// elements of the array arr
int temp[] = new int[size];
int index = 0;
for(int i = size - 1; i >= 0; i--)
{
temp[i] = arr[index];
index = index + 1;
}
return temp;
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr
ReverseArr obj = new ReverseArr();
// input array - 1
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
// computing the length
int len = arr.length;
int ans[] = obj.reverseArray(arr);
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans[i] + " ");
}
System.out.println("\n ");
// input array - 2
int arr1[] = {4, 8, 3, 9, 0, 1};
// computing the length
len = arr1.length;
int ans1[] = obj.reverseArray(arr1);
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans1[i] + " ");
}
}
}
Output:
For the input array:
1 2 3 4 5 6 7 8
The reversed array is:
8 7 6 5 4 3 2 1
For the input array:
4 8 3 9 0 1
The reversed array is:
1 0 9 3 8 4
Analyzing Complexity: The program utilizes a for loop to reverse the array, resulting in a time complexity of O(n). Additionally, the program necessitates an auxiliary array for the array reversal, leading to a space complexity of O(n), where n represents the total quantity of elements within the array.
Approach 2: Using Two Pointers
Another method to reverse an array involves utilizing two pointers. The initial pointer is positioned at the beginning of the array while the second pointer is placed at the end of the array. Subsequently, we interchange the elements indicated by these two pointers. Following the swap, the second pointer shifts leftward, and the first pointer moves rightward. The swapping process continues until the two pointers converge or pass each other, at which point the reversal process is complete, resulting in the reversed array.
FileName: ReverseArr1.java
public class ReverseArr1
{
// method for reversing an array
public int[] reverseArray(int arr[])
{
// computing the size of the array arr
int size = arr.length;
// two pointers for reversing
// the input array
int ptr1 = 0;
int ptr2 = size - 1;
// reversing the input array
// using a while loop
while(ptr1 < ptr2)
{
int temp = arr[ptr1];
arr[ptr1] = arr[ptr2];
arr[ptr2] = temp;
ptr1 = ptr1 + 1;
ptr2 = ptr2 - 1;
}
return arr;
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr1
ReverseArr1 obj = new ReverseArr1();
// input array - 1
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
// computing the length
int len = arr.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
int ans[] = obj.reverseArray(arr);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans[i] + " ");
}
System.out.println("\n ");
// input array - 2
int arr1[] = {4, 8, 3, 9, 0, 1};
// computing the length
len = arr1.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
int ans1[] = obj.reverseArray(arr1);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans1[i] + " ");
}
}
}
Output:
For the input array:
1 2 3 4 5 6 7 8
The reversed array is:
8 7 6 5 4 3 2 1
For the input array:
4 8 3 9 0 1
The reversed array is:
1 0 9 3 8 4
Analysis of Complexity: The time complexity of this program remains unchanged compared to the previous version. No additional space is utilized, resulting in a space complexity of O(1) for the program.
Approach 3: Using Stack
Because of its Last In First Out (LIFO) nature, a Stack is ideal for reversing an input array. To achieve this, we simply push all elements of the input array onto the stack from left to right. This can be accomplished by iterating through the array using a loop.
FileName: ReverseArr2.java
// importing Stack
import java.util.Stack;
public class ReverseArr2
{
// method for reversing an array
public int[] reverseArray(int arr[])
{
// computing the size of the array arr
int size = arr.length;
Stack<Integer> stk = new Stack<Integer>();
// pusing all the elements into stack
// starting from left
for(int i = 0; i < size; i++)
{
stk.push(arr[i]);
}
int i = 0;
while(!stk.isEmpty())
{
int ele = stk.pop();
arr[i] = ele;
i = i + 1;
}
return arr;
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr2
ReverseArr2 obj = new ReverseArr2();
// input array - 1
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
// computing the length
int len = arr.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
int ans[] = obj.reverseArray(arr);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans[i] + " ");
}
System.out.println("\n ");
// input array - 2
int arr1[] = {4, 8, 3, 9, 0, 1};
// computing the length
len = arr1.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
int ans1[] = obj.reverseArray(arr1);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans1[i] + " ");
}
}
}
Output:
For the input array:
1 2 3 4 5 6 7 8
The reversed array is:
8 7 6 5 4 3 2 1
For the input array:
4 8 3 9 0 1
The reversed array is:
1 0 9 3 8 4
Analysis of Complexity: The time complexity of the current program remains unchanged from the previous one. The presence of a stack in the program results in a space complexity of O(n).
Using Recursion
By employing recursion as well, we can accomplish the identical outcome. Consider the following example.
FileName: ReverseArr3.java
// importing ArrayList
import java.util.ArrayList;
public class ReverseArr3
{
ArrayList<Integer> reverseArr;
// constructor of the class
ReverseArr3()
{
reverseArr = new ArrayList<Integer>();
}
// method for reversing an array
public void reverseArray(int arr[], int i, int size)
{
// dealing with the base case
if(i >= size)
{
return;
}
// recursively calling the method
reverseArray(arr, i + 1, size);
reverseArr.add(arr[i]);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr3
ReverseArr3 obj = new ReverseArr3();
// input array - 1
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
// computing the length
int len = arr.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
obj.reverseArray(arr, 0 , len);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(obj.reverseArr.get(i) + " ");
}
System.out.println("\n ");
obj = new ReverseArr3();
// input array - 2
int arr1[] = {4, 8, 3, 9, 0, 1};
// computing the length
len = arr1.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
obj.reverseArray(arr1, 0, len);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(obj.reverseArr.get(i) + " ");
}
}
}
Output:
For the input array:
1 2 3 4 5 6 7 8
The reversed array is:
8 7 6 5 4 3 2 1
For the input array:
4 8 3 9 0 1
The reversed array is:
1 0 9 3 8 4
In this scenario, the reverseArr.add(arr[i]); command is placed subsequent to the recursive call entering the stack (notably, the stack is implicit in this instance). Consequently, as the base case is reached within the recursive call, the stack starts to unwind, causing the items within it to be removed. The final item added to the stack during the ultimate recursive call will be the first one to be removed. Subsequently, the second-to-last item will be removed, and so forth. The reverseArr.add(arr[i]); instruction captures these removed elements. Ultimately, the elements stored in the reverseArr list are exhibited.
Analysis of Complexity: Equivalent to the initial program in the third approach.
Approach 4: Using Collections.reverse method
The reverse method from the Collections class is utilized to invert the order of a list. An illustration of its application is demonstrated in the subsequent code snippet.
FileName: ReverseArr4.java
// importing Collections, Arrays, ArrayList & List
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class ReverseArr4
{
// method for reversing an array
public List<Integer> reverseArray(Integer arr[])
{
List<Integer> l = (Arrays.asList(arr));
Collections.reverse(l);
return l;
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr4
ReverseArr4 obj = new ReverseArr4();
// input array - 1
Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
// computing the length
int len = arr.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
List<Integer> ans = obj.reverseArray(arr);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans.get(i) + " ");
}
System.out.println("\n ");
// input array - 2
Integer arr1[] = {4, 8, 3, 9, 0, 1};
// computing the length
len = arr1.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
ans = obj.reverseArray(arr1);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans.get(i) + " ");
}
}
}
Output:
For the input array:
1 2 3 4 5 6 7 8
The reversed array is:
8 7 6 5 4 3 2 1
For the input array:
4 8 3 9 0 1
The reversed array is:
1 0 9 3 8 4
Analysis of Complexity: The software employs the Collections.reverse function, which efficiently reverses the list in a linear fashion, resulting in a time complexity of O(n). By utilizing a list, the program incurs a space complexity of O(n), where n represents the overall count of elements within the array.
Note 1: Collections.reverse method is also used to reverse the linked list.
Note 2: All the approaches discussed above are applicable to different data types too.
Approach 5: Using StringBuilder.append method
The title indicates that this technique is suitable for arrays of strings. By employing the StringBuilder.append function, we can invert the string array by sequentially appending its elements from the end to the beginning.
FileName: ReverseArr5.java
import java.util.*;
public class ReverseArr5
{
// method for reversing an array
public String[] reverseArray(String arr[])
{
StringBuilder reversedSB = new StringBuilder();
for (int j = arr.length; j > 0; j--)
{
reversedSB.append(arr[j - 1]).append(" ");
};
String[] reversedArr = reversedSB.toString().split(" ");
return reversedArr;
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ReverseArr5
ReverseArr5 obj = new ReverseArr5();
// input array - 1
String arr[] = {"Java", "is", "the", "best", "website"};
// computing the length
int len = arr.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr[i] + " ");
}
String[] ans = obj.reverseArray(arr);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans[i] + " ");
}
System.out.println("\n ");
// input array - 2
String arr1[] = {"India", "is", "my", "country"};
// computing the length
len = arr1.length;
System.out.println("For the input array: ");
for(int i = 0; i < len; i++)
{
System.out.print(arr1[i] + " ");
}
String[] ans1 = obj.reverseArray(arr1);
System.out.println();
System.out.println("The reversed array is: ");
for(int i = 0; i < len; i++)
{
System.out.print(ans1[i] + " ");
}
}
}
Output:
For the input array:
Java is the best website
The reversed array is:
website best the is Java
For the input array:
India is my country
The reversed array is:
country my is India
Analysis of Complexity: The time and space efficiency of the software is equivalent to that of the preceding program.