In this tutorial, I am going to discuss how to reverse an array without using another array.
Given an array of integers, write a code to reverse an array in-place.
For Example –
Input : {1, 7, 8, 9}
Output: { 9, 8, 7, 1}
We have to reverse an array without using extra space. How do you approach this problem?
Segregate 0s and 1s in an array
Reverse an Array without using Another Array – Java Code
We can solve this problem in-place by using two pointers.
We declare two pointers start and end. The initial value of Start variable is zero and the initial value of end variable is with array length minus one. Then we run a loop until the value of start is less than end. We swap the values present at start and end index. Then we increment the value of start variable and decrement the value of end variable.
The time complexity of this approach is O(n) and it’s space complexity is O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
//Reverse array without using extra space - Java Code public class ReverseArray { public static void reverse(int[] arr) { //Declare two variables start and end int start = 0; int end = arr.length - 1; //Run a loop while start is less than end while(start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static void main(String[] args) { int[] arr = {1, 7, 8, 9}; reverse(arr); System.out.println(" After reversing an array "); for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } } |