Program for reverse an array of integers in java

 Problem :- Write a program to reverse an array in java.

Solution: There are multiple approaches to solve this problem , here in example we have solved it using normal loop and recursion .

1. Using Loop :  In this approach we will loop the array until start index is less than end index and swap the values of array with corresponding index .

Steps:- 

  • assign variable with index start=0 and end = len-1
  • loop array while start > end 
  • swap the array elements with help of temp
  • increase the start index as it will move forward 
  • decrease the end index as it will move backward 
  • print array 

private static void reverseUsingLoop(int[] ar) {
int start=0,end=ar.length-1;
while (start<end){
int temp=ar[start];
ar[start]=ar[end];
ar[end]=temp;
start++;
end--;
}
}


Time Complexity : O(n)  , as it will loop n/2 times .

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

2. Using recursion : It is the similar approach as looping the key diff is that we use recursion instead of loop.

Steps:-
  • define the termination condition as start index >= end index 
  • swap the array elements with help of temp
  • call method with changing the index .


private static void reverseUsingRecursion(int[] ar,int start,int end) {
if(start>=end)return;
int temp=ar[start];
ar[start]=ar[end];
ar[end]=temp;
reverseUsingRecursion(ar,start+1,end-1);
}


Time Complexity : O(n)  

__________________________________________________________

output:- 

output: reverse of array with execution time









 You can found the full program on below link - reverse-array-in-java


Thanks .