简体   繁体   中英

Reverse the order of array in java?

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.

Your reverseArray() method assigns array to the variable revArray , thus the 2 variables pointing the same array in memory.

To avoid that, try something like this:

public static int[] reverseArray(int[] array){
    int[] revArray= Arrays.copyOf(array, array.length);
    int i=0;
    int j=revArray.length-1;
    while(i<=j){
        swap(i,j,revArray);
        j--;
        i++;
    }
    return revArray;
}

As it has been mentioned in the comments, the problem is you are refering to the same array in. So, when you change it in the methods, it changes the original. But, to reverse an array you don't need this much of a complexity. check this:

int[] array={2,4,6,8,10,12,14,16};
int length = array.length;
int[] array1 = new int[length];
for(int i = 0 ; i < length; i++) {
  array1[length - 1 - i] = array[i];
}
System.out.println(Arrays.toString(array1)); // prints [16, 14, 12, 10, 8, 6, 4, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM