I am trying to write a function to reverse array, but it doesn't work like I want to.
public class ReverseArray{
public static int[] reverseArray(int[] array){
int[] revArray=array;
int i=0;
int j=revArray.length-1;
while(i<=j){
swap(i,j,revArray);
j--;
i++;
}
return revArray;
}
public static void swap(int i, int j, int[] revArray){
int temp;
temp=revArray[i];
revArray[i]=revArray[j];
revArray[j]=temp;
}
public static void main(String []args){
int[] array={2,4,6,8,10,12,14,16};
int[] revArray=reverseArray(array);
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
System.out.println();
for(int i=0;i<revArray.length;i++){
System.out.print(revArray[i]+" ");
}
}
}
Output:16 14 12 10 8 6 4 2
16 14 12 10 8 6 4 2
But when I do it like this:
int[] array={2,4,6,8,10,12,14,16};
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
int[] revArray=reverseArray(array);
System.out.println();
for(int i=0;i<revArray.length;i++){
System.out.print(revArray[i]+" ");
}
Output:2 4 6 8 10 12 14 16
16 14 12 10 8 6 4 2
I don't understand why both arrays are reversed if I call the function revArray before I print them.