In this post we’ll see how to reverse an array in-place Java. Though it is easy to take another array and start storing elements from the last index to the first index of the original array to this new array in order to get reversed array but this approach means using auxiliary data structure, a new array to store the reversed elements making the space complexity of this approach O(n).
Using an in-place algorithm means additional space is not used and the space provided by the input data structure itself is used to modify the elements to get the output. Thus the Java program to reverse an array in-place will not use any additional array and swap elements with in the original array to get the reversed array as output.
Reverse array in-place Java program
One thing to note here is that you don’t need to iterate the whole array, you need to iterate only n/2 array for the array of size n. Since the first and last elements, second and second last and so on are swapped in each iteration so by the time middle element is reached the array is already reversed.
import java.util.Arrays; public class ArrayReverseInplace { public static void main(String[] args) { int[] arr = {61, 34, 10, 0, 15, 112, 53, 78, 39, 68}; reverseArray(arr); } static void reverseArray(int[] arr) { int n = arr.length; int temp; // Iterate till array length/2 for (int i = 0; i < n / 2; i++) { temp = arr[i]; // Swapping arr[i] = arr[n - i - 1]; arr[n - i - 1] = temp; } System.out.println("Reversed Array- " + Arrays.toString(arr)); } }Output
Reversed Array- [68, 39, 78, 53, 112, 15, 0, 10, 34, 61]
As you can see in the Java program for reversing array in-place same input array space is used to do the reversal, only extra space required is for the auxiliary variables used.
That's all for the topic Reverse an Array In-place Java Program. If something is missing or you have something to share about the topic please write a comment.
You may also like
- How to Reverse a String in Java
- How to Reverse a Number in Java
- Shallow Copy Vs Deep Copy in Java Object Cloning
- Convert ArrayList to Array in Java
- Java StringJoiner Class With Method Examples
- Spring Boot Application Using Spring Initializr
- Fix LazyInitializationException: could not initialize proxy Error
- Spring Data JPA Pagination and Sorting Example
No comments:
Post a Comment