In this article we are discuss about Basic Problem in Programming. How To Reverse a Array Elements.
Reverse a given array elements. For example1,
[1,2,3,4,5]
Output
[5,4,3,2,1]
example2,
Input
[3,5,1,2,4]
Output
[4,2,1,5,3]
1) With Extra Space (Copy Arrar)
We can simple make a same size of array and copy from given array elements to new array variable.
Its takes o(n) Time Complexity. And more Space To Run Programme.
class arrayReverse{
public static void main(String[] args){
int[] arr={1,2,3,4,5};
int n=arr.length;
int[] brr=new int[n];
for(int i=0;i<n;i++){
brr[i]=arr[n-i-1];
}
for(int j=0;j<n;j++){
System.out.println(brr[j]);
}
}
}
2)With Out Extra Space.
We can Swap The Array Element One By One. Like First Element And Last. Second Element And Second Last Until Reach Middle Element.
class arrayReverseWithoutExtraSpace{
public static void main(String[] args){
int[] arr={1,2,3,4,5,6};
int n=arr.length;
int i=0;
int j=n-1;
while(i<j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i+=1;
j-=1;
}
for(int k=0;k<n;k++){
System.out.println(arr[k]);
}
}
}
Comments
Post a Comment